Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

292
Visualizações
Java read textfile and combining different lines together

Lets say we have the following text file with an ID(non unique),Name, and Number

1 Hello 3
1 Goodbye 2
1 Hello 6
1 Goodbye 5

They are not on the same line and I would like to be able to add them together and put that to a variable. These would not necessary be right next to each other like this so it would need to be in a if statement if id and name are both similar then add the numbers.

I would like to be able to get this as my output

Hello 9
Goodbye 7 

So it would have to read the whole file before outputting anything, how would this be done?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

    File file = new File("your/file/path");
    String line = "";
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {

        while ((line = reader.readLine()) != null) {
            // the algorithm that YOU should develop
            //or fail to develop and ask about to group things etc.
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }
over 4 years ago · Santiago Trujillo Relatório

0

Here's a quick and dirty solution that uses Java 8 stream api and Java 7 NIO.2 api:

// read all lines from the file
Files.readAllLines(Paths.get("<path_to_your_file>"))
        // begin the stream
        .stream()
        // split every line by whitespaces
        // to get arrays like [1, "Hello", 3], [1, "Goodbye", 2]...
        .map(s -> s.split("\\s+"))
        // collecting to a map, grouping by the String {firstColumn}-{secondColumn}
        .collect(Collectors.groupingBy(split -> split[0] + "-" + split[1],
                // downstream collector sums the 3rd column after parsing them as long
                Collectors.summingLong(split -> Long.parseLong(split[2]))))
        // so we have Map<String, Long> with entries like {1-Hello -> 9}, {2-Goodbye -> 7}
        .forEach((key, value) ->
                // we print these entries one each line (println)
                // by taking the part after dash of key,
                // and a space between key and value, like: Hello 9
                System.out.println(key.split("-")[1] + " " + value));

Please note that this solution is far from complete, for example:
1- Reads the whole file into memory so if the file is too big it can cause problem (large allocated heap, OutOfMemoryErrors etc). Would be better if it was done by streaming.

2- If the "Name" is allowed to have whitespaces, splitting with whitespace will fail - that would need some extra work. The solution assumes every line has exactly 3 "columns", separated by whitespace.

3- If the "Name" is allowed to have dash (-), splitting by dash while prining the output would give incorrect result. Actually, grouping should be done using a separate classifier class, or something line a Tuple or Entry.

4- Solution assumes 3rd column is always a parseable long, and the sum does not go beyond the boundaries of Long.

But at least it can give you which steps to follow. You can do your proper implementation with similar steps.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda