3

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);

            }
        }
2
  • What's the question? Commented Mar 11, 2019 at 21:42
  • @Fureeish: How to create objects using stream and read params from a file. It's already been solved. Thanks Commented Mar 11, 2019 at 23:23

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Or s.split(" ", 2), so it doesn’t search for additional occurrences of the delimiter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.