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?
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?
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 = ...
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());