My Question is inspired by this Question, but is aimed at using Java Streams to arrive an a List<Integer>.
I have this code that kind of works. It seems to be returning an ArrayList, presumably ArrayList<Integer>. But the compiler refuses to let me declare the result as such.
String input = "1 2 3 4 5";
Stream stream = Arrays.stream( input.split( " " ) );
var x = stream.map( s -> Integer.valueOf( ( String ) s ) ).collect( Collectors.toList() );
This runs when using the new var feature of recent Java versions.
System.out.println( x.getClass() );
System.out.println( x );
class java.util.ArrayList
[1, 2, 3, 4, 5]
I have two questions:
- Why is
xreported as anArrayListyet I cannot declarexto be an ArrayList (error: incompatible types), such as:ArrayList<Integer> x = stream.map( s -> Integer.valueOf( ( String ) s ) ).collect( Collectors.toList() ); - Is there a better way to use streams to convert this string of digits to a
ListofInteger?
Stream<String> stream.var x = input.chars().filter(c -> c != 32).map(c -> c-'0').boxed().collect(Collectors.toList());