Given:

public class Product {

    int id;
    int price;

    public Product(int id, int price) {
        this.id = id;
        this.price = price;
    }

    public String toString() {
        return id + " : " + price;
    }
}

and the code fragment:

List<Product> products = new ArrayList(Arrays.asList(new Product(1, 10),
        new Product(2, 30),
        new Product(3, 20)));
Product p = products.stream().reduce(new Product(4, 0), (p1, p2) -> {
    p1.price += p2.price;
    return new Product(p1.id, p1.price);
});
products.add(p);
products.stream().parallel()
        .reduce((p1, p2) -> p1.price > p2.price ? p1 : p2)
        .ifPresent(System.out::println);

What is the result?

A.

2 : 30

B.

4 : 0

C.

4 : 60

D.

4 : 60
2 : 30
3 : 20
1 : 10

E. The program prints nothing.

题解

程序第 33 行,reduce 方法会将串流中的所有 Product 对象元素的 price 字段进行加总,10+30+20=60,最后得到的 Product 对象为「4 : 60」。

程序第 39 行,reduce 方法会保留最后 price 字段数值最大的 Product 对象,因此会把「4 : 60」留下。

程序第 40 行,输出「4 : 60」。