Java 8 Streams parsing to Integer

Spongi :

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());
Eran :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=458877&siteId=1