Java Stream Collectors. Tolist() does not compile
•
Java
Anyone can explain why the following code can't be compiled, but what about the second code?
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); }
Compile errors on collection lines
>Method collect (supplier, objintconsumer, biconsumer) in intstream type is not applicable to parameter (Collector >) > type mismatch: cannot convert > from collector to supplier
compile
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); }
Solution
Intstream does not accept the collector's collect method If you want a list < integer >, you must package intstream into a stream < integer >:
out = IntStream .range(1,10) .filter(e -> e % 2 == 0) .map(e -> 2 * e) .@R_786_2419@ed() .collect(Collectors.toList());
. map().@ R_ 786_ 2419@ed The alternative to () is maptoobj ():
out = IntStream .range(1,10) .filter(e -> e % 2 == 0) .mapToObj(e -> 2 * e) .collect(Collectors.toList ());
Alternatively, you can use the intstream collection method:
out = IntStream .range(1,10) .filter(e -> e % 2 == 0) .map(e -> 2 * e) .collect(ArrayList<Integer>::new,ArrayList::add,ArrayList::addAll);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码