Can any one explain why the below code will not compile but the second one does?
Do not compile
private void doNotCompile() {
List<Integer> out;
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.map(e -> Integer.valueOf(2 * e))
.collect(Collectors.toList());
System.out.println(out);
}
Compilation errors on the collect line
Compiles
private void compiles() {
List<Integer> in;
in = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<Integer> out;
out = in.stream()
.filter(e -> e % 2 == 0)
.map(e -> 2 * e)
.collect(Collectors.toList());
System.out.println(out);
}
IntStream doesn't have a collect method that accepts a Collector. If you want a List<Integer>, you have to box the IntStream into a Stream<Integer>:
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.map(e -> 2 * e)
.boxed()
.collect(Collectors.toList());
An alternative to .map().boxed() is mapToObj():
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.mapToObj(e -> 2 * e)
.collect(Collectors.toList ());
or you can use the IntStream collect method:
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.map(e -> 2 * e)
.collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With