我想处理一个列表,然后计算处理了多少项目。我的代码是这样的:
List<String> names = ...;
names.stream().filter(...).map(...) /* a list of time-consuming filters and maps */
.forEach(...);
// Then count them:
int count = names.stream().filter(...).map(...).count();
如果我想像这样简化我的代码使用供应商:复制流以避免“流已被操作或关闭”,我仍然需要执行两次耗时的过滤器和映射列表。
所以我必须以一种丑陋的方式来做,比如:
List<String> filteredNames = names.stream().filter(...).map(...).collector(Collectors.toList());
filteredNames.forEach(...);
int count = filteredNames.size();
这可能会在 Java 堆上生成另一个巨大的列表。
一个更丑陋但有效的方法是:
int[] count = {0}; // or use AtomicInteger(0);
names.stream().filter(...).map(...).forEach(s -> {
// process
count[0] ++;
});
有没有一种优雅的方式来做到这一点?