Java 8 Streams parsing to Integer

513
June 26, 2017, at 00:51 AM

Does it exist better way to parse String to Integer using stream than this :

 String line = "1 2 3 4 5";
List<Integer> elements = Arrays.stream(line.split(" ")).mapToInt(x -> Integer.parseInt(x))
    .boxed().collect(Collectors.toList());
Answer 1

You can eliminate one step if you parse the String directly to Integer:

String line = "1 2 3 4 5";
List<Integer> elements = Arrays.stream(line.split(" ")).map(Integer::valueOf)
    .collect(Collectors.toList());

Or you can stick to primitive types, which give better performance, by creating an int array instead of a List<Integer>:

int[] elements = Arrays.stream(line.split(" ")).mapToInt(Integer::parseInt).toArray ();

You can also replace

Arrays.stream(line.split(" "))

with

Pattern.compile(" ").splitAsStream(line)

I'm not sure which is more efficient, though.

Answer 2

There's one more way to do it that will be available since java-9 via Scanner#findAll:

int[] result = scan.findAll(Pattern.compile("\\d+"))
                   .map(MatchResult::group)
                   .mapToInt(Integer::parseInt)
                   .toArray();
Rent Charter Buses Company
READ ALSO
Editing a contact&#39;s lastname not working on some APIs

Editing a contact's lastname not working on some APIs

I have a code to edit a contact's last name to "anyname" and it works fine on some APIs and doesn't work on the othersThe main code starts by touching a button with this code:

271
How to make a high-performance matrix algorithm implementation distributed?

How to make a high-performance matrix algorithm implementation distributed?

I have a multithreaded program where the number of cores is the bottleneck for speedAlmost all memory is used by a triangular matrix

367
Jcommander usage formatting

Jcommander usage formatting

Hey I am using Jcommander library to parse command line argumentsMy problem is with the format of the usage message generated by the Jcommander

631
ImageIO writes only the background colour but not the graphics

ImageIO writes only the background colour but not the graphics

I've got the following statement to write a buffered jPanel image onto apng file

310