Java 流 Collectors.toList() 无法编译

Java Stream Collectors.toList() wont 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);
}

collect 行出现编译错误

编译

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 没有接受 Collectorcollect 方法。如果你想要 List<Integer>,你必须将 IntStream 装箱成 Stream<Integer>:

out = IntStream
        .range(1, 10)
        .filter(e -> e % 2 == 0)
        .map(e -> 2 * e)
        .boxed()
        .collect(Collectors.toList());

.map().boxed() 的替代方法是 mapToObj():

out = IntStream
        .range(1, 10)
        .filter(e -> e % 2 == 0)
        .mapToObj(e -> 2 * e)
        .collect(Collectors.toList ());

或者你可以使用IntStreamcollect方法:

out = IntStream
        .range(1, 10)
        .filter(e -> e % 2 == 0)
        .map(e -> 2 * e)
        .collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll);

IntStreamcollect方法在不可编译的情况下是不同的。

public <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner)

因此它不接受您提供给 collect

的参数

您可以通过将 List<Integer> 转换为 IntStream

来解决这个问题

在第一个示例中,您正在对原始整数流进行操作。原始整数不能进入 Listbasically because generics in Java are less than ideal. Java language designers are working on potentially fixing this.

同时,为了解决这个问题,您需要将这些原始整数装箱到 Integer wrapper first. See 中作为代码示例。

在第二个示例中,您已经迭代了 Integers,所以 它正常工作™。


I thought I was boxing those int to Integers when I did Integer.valueOf in the mapper

map function of IntStream takes a IntUnaryOperator 是一个接受原始 int 和 returns 原始 int 的函数式接口。

您从 valueOf 获得的 Integer 已拆箱以匹配功能界面。