Java 8 Syntax Analysis for Integer

Is there a better way to parse a String string for Integer using a 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()); 
+5
source share
2 answers

You can exclude one step if parsing the string directly in 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 with primitive types that give better performance by creating an int array instead of 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 am not sure which is more efficient.

+9
source

There is another way to do this that will be available with java-9 through Scanner#findAll :

 int[] result = scan.findAll(Pattern.compile("\\d+")) .map(MatchResult::group) .mapToInt(Integer::parseInt) .toArray(); 
+3
source

Source: https://habr.com/ru/post/1269200/


All Articles