使用java 8流计算单次传递多个项目

Sha*_*hay 4 java java-stream

假设我有以下课程:

class Z {
    X x;
    Y y;
}
Run Code Online (Sandbox Code Playgroud)

我有一个Z元素列表.我想在一次通过中计算在x字段中有多少元素的值x1,以及在y字段中有多少元素具有值y1.

使用循环是直截了当的:

int countOfx1 = 0;
int countOfy1 = 0;
for (Z z: list) {
    if (z.x == x1) {
        countOfx1++
    }
    if (z.y == y1) {
        countOfy1++
    }
 }
Run Code Online (Sandbox Code Playgroud)

它可以简单地使用流吗?

spr*_*ter 6

您可以通过为总计创建收集器来完成此操作:

class Zcount {
    private int xCount = 0;
    private int yCount = 0;

    public Zcount accept(Z z) {
        if (z.x == x1)
            xCount++;
        if (z.y == y1)
            yCount++;
        return this;
    }

    public Zcount combine(ZCount other) {
        xCount += other.xCount;
        yCount += other.yCount;
        return this;
    }
}

Zcount count = list.stream().collect(Zcount::new, Zcount::accept, Zcount::combine);
Run Code Online (Sandbox Code Playgroud)

这比迭代解决方案具有优势,您可以使流并行,如果列表非常大,则可以具有性能优势.