Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!