Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

291
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda