-3

For arrays we can use:

int[] arr = Arrays.stream(br.readLine().trim.split("\\s+"))
            .maptoInt(Integer::parseInt)
            .toArray();

Is there any similar way to initialize List in 1 step?

Pratyush
  • 1
  • 4

2 Answers2

0

Use the autoboxing methods and collect into a list instead of calling toAray()

...
.boxed().collect(Collectors.toList());

NB: Your variable would be a list like List<Integer> intList = ...

elman
  • 11
  • 1
0

If you have multiple lines in a file of just ints separate by whitespace you can read then all into a list as follows:

List<Integer> list = null;
try {
    list = Files.lines(Path.of("c:/someFile.txt"))
            .flatMap(line -> Arrays.stream(line.trim().split("\\s+")))
            .map(Integer::parseInt)
            .collect(Collectors.toList());
} catch (IOException ioe) {
    ioe.printStackTrace();
}

To read in a single line as in your example, you can do it like this.

List<Integer> list = Arrays.stream(br.readLine().trim().split("\\s+"))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
WJS
  • 30,162
  • 4
  • 20
  • 36