java - 在java 8流中的过滤器方法中做另一个过程是否可以
问题描述
我知道如何根据条件过滤集合并收集。我想知道在过滤器中执行另一个过程是否可以。
List<SupplementaryCustomer> supplementaryCustomersWithMoreThan100Points = new ArrayList<>();
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(c -> {
boolean isOkay = c.getPoints() > 100;
if(isOkay && (c.isSupplementaryCustomer())){
SupplementaryCustomer.add(c);
}
return isOkay;
})
.collect(Collectors.toList());
假设客户对象具有所有类型的客户。我需要获得超过 100 分的补充客户和超过 100 分的客户。我在我的代码库中做这样的事情。可以做这样的事情吗?
解决方案
流应该没有副作用,除了用于副作用的终端操作(foreach)。您正在做的事情违反了这种范式。如果您的列表中没有数百万个项目,那么再次流式传输结果列表然后按您的其他标准过滤以添加到其他列表的成本可以忽略不计,即使那样我也提倡反对违反语言范式以获得小的性能促进。
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(c -> c.getPoints() > 100)
.collect(Collectors.toList());
List<SupplementaryCustomer> supplementaryCustomersWithMoreThan100Points = customersWithMoreThan100Points
.stream()
.filter(c -> c.isSupplementaryCustomer())
.collect(Collectors.toList());
它更容易阅读、更简单、更符合 Streams 的意图,我怀疑在任何典型用例中你会发现明显的(甚至可测量的)性能损失。
推荐阅读
- python - 金字塔设置类型转换
- c# - Why are several executions of an eventhandler triggered from the same thread if I am invoking the event from a different thread each time?
- ios - 无法与 UIView 中的任何内容进行交互
- database - 无法在 Windows 上使用 Psycopg2 连接到 Postgres
- django - 将一个表单域的值替换为另一个
- javascript - 无论如何,使用最后一个参数反应事件处理程序
- python - Vim for Python 中的自动缩进
- java - 父类中不存在被覆盖方法中的变量
- swift - 在 UIView 上添加两个不同颜色的阴影?
- sql - 获取特定列的总和以及最后一行中另一列的值