-2

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
  • 13
  • 5

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
  • 9
  • 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
  • 36,363
  • 4
  • 24
  • 39