Java 8 Stream Multiple Object Creation from an input File

USQ91 :

I'm trying to read a file to capture parameters to be passed to objects using Java 8 stream.

The file format is:

10 AA

15 BB

20 CC

Same number of objects have to be created as the number of lines, the objects take these parameters.

e.g Object a = new Object(10 , AA).

The file will always have a maximum of 3 lines.

I've come as far as reading the file, checking if it starts with a digit, splitting it at new line and placing each line in a List of String[ ].

     List<String[]> input = new ArrayList<>();

        try {

          input =  Files.lines(Paths.get("C:\\Users\\ubaid\\IntelliJ Workspace\\Bakery\\input.txt")).
                    filter(lines->Character.isDigit(lines.trim().charAt(0))).map(x-> x.split("\\r?\\n")).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }

        for(String a[] : input){
            for(String s : a){
                System.out.println(s);

            }
        }
Karol Dowbecki :

Assuming you have:

public class Type {
  private int number;
  private String text;
  // constructor and other methods
}

And the file is well formatted:

List<Type> objs = Files.lines(path)
    .map(s -> s.split(" "))
    .map(arr -> new Type(Integer.parseInt(arr[0]), arr[1]))
    .collect(Collectors.toList());
System.out.println(objs);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96524&siteId=1