首页 > 解决方案 > 在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 分的客户。我在我的代码库中做这样的事情。可以做这样的事情吗?

标签: javafilterjava-8java-streamcollectors

解决方案


流应该没有副作用,除了用于副作用的终端操作(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 的意图,我怀疑在任何典型用例中你会发现明显的(甚至可测量的)性能损失。


推荐阅读