使用java 8流计算单次传递多个项目
发布时间:2020-12-15 04:35:26 所属栏目:Java 来源:网络整理
导读:假设我有以下课程: class Z { X x; Y y;} 我有一个Z元素列表.我想在一次传递中计算在x字段中有多少元素的值x1,以及在y字段中有多少元素具有值y1. 使用循环是直截了当的: int countOfx1 = 0;int countOfy1 = 0;for (Z z: list) { if (z.x == x1) { countOfx
假设我有以下课程:
class Z { X x; Y y; } 我有一个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++ } } 它可以简单地使用流吗? 解决方法
您可以通过为总计创建收集器来完成此操作:
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); 这比迭代解决方案具有优势,您可以使流并行,如果列表非常大,则可以具有性能优势. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |