Home > Software engineering >  Read comma separated values from a text file in Java and find the maximum number from each line
Read comma separated values from a text file in Java and find the maximum number from each line

Time:09-24

I used the following code to read all the lines. Now as I understand it I should somehow parse the numbers from each line and apply a function to get the maximum value. The problem is I do not know how to go about it and I do not know what to search for in google. The problem is one of unknown unknowns. Some pointers would be helpful.

import java.io.IOException;
import java.util.List;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.ArrayList;

public class KnowNotTest1 {
    public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    System.out.println("Using Path.readAllLines()");
    try{
        List<String> fileData = Files.readAllLines(Paths.get("files\\b.txt"));
        fileData.forEach(System.out::println);
    }
    catch (IOException e){
        System.out.println(e);
    }
}

}

The text file I am reading is as below:

10,11,12
2,13
33,22,1,1
1

And the expected output is:

12
13
33
1

CodePudding user response:

Without checking the input file is correct

readAllLines(Paths.get("/tmp/lines.txt")).stream()
        .mapToInt(s -> Arrays.stream(s.split(","))
                .mapToInt(Integer::parseInt).max().getAsInt())
        .forEach(System.out::println);

the previous one is the best one to do, not directly (there are three important and decoupled parts: read, compute and report) also, it open te door to process in a efficient, online, streaming way (readAllLines break it).

An imperative way is

for(String line: readAllLines(Paths.get("/tmp/lines.txt"))) {
    int max = Integer.MIN_VALUE;
    for (String word : line.split(","))
        max = Math.max(max, Integer.parseInt(word));
    System.out.println(max);
}

but is coupled and not compose.

CodePudding user response:

Use mapToXX method of stream api :

public class KnowNotTest1 {
    public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    System.out.println("Using Path.readAllLines()");
    try{
        List<String> fileData = Files.readAllLines(Paths.get("files\\b.txt"));
        
        System.out.println("Input: ");
            fileData.forEach(System.out::println);

            System.out.println("Output: ");
            fileData.stream()
                    .mapToLong(
                            s -> Arrays.stream(s.split(","))
                                    .mapToLong(Long::parseLong).max()
                                    .getAsLong()).forEach(System.out::println);
    }
    catch (IOException e){
        System.out.println(e);
    }
}
  • Related