在Java8流中的filter方法中执行另一个进程可以吗

在Java8流中的filter方法中执行另一个进程可以吗,java,filter,java-8,java-stream,collectors,Java,Filter,Java 8,Java Stream,Collectors,我知道如何根据条件筛选集合并收集。我想知道是否可以在过滤器内执行另一个过程 List<SupplementaryCustomer> supplementaryCustomersWithMoreThan100Points = new ArrayList<>(); List<Customer> customersWithMoreThan100Points = customers .stream() .filter(c -> { boolea

我知道如何根据条件筛选集合并收集。我想知道是否可以在过滤器内执行另一个过程

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()); 

List supplementarycusterwiththan 100points=new ArrayList();
列出得分超过100分的客户=客户
.stream()
.过滤器(c->{
布尔isOkay=c.getPoints()>100;
if(isOkay&(c.isSupplementaryCustomer()){
补充客户。添加(c);
}
返回isOkay;
})
.collect(Collectors.toList());

假设客户对象具有所有类型的客户。我需要获得100分以上的补充客户和100分以上的客户。我正在我的代码库中做类似的事情。这样做可以吗?

流应该没有副作用,但用于副作用(foreach)的终端操作除外。你所做的违反了这个范式。如果列表中没有数以百万计的项目,那么再次流式处理结果列表,然后按其他标准过滤以添加到其他列表的成本是可以忽略的,即使这样,我也不主张违反languager范例来获得一点性能提升

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());
列出得分超过100分的客户=客户
.stream()
.filter(c->c.getPoints()>100)
.collect(Collectors.toList());
列出积分超过100分的补充客户=积分超过100分的客户
.stream()
.filter(c->c.isSupplementaryCustomer())
.collect(Collectors.toList());

它更易于阅读,不太复杂,更符合流的意图,我怀疑您在任何典型的用例中都不会发现明显的(甚至可以测量的)性能损失。

不,因为某些原因。1-杀戮可读性2-有副作用H,是的。仅仅是对象
SupplementaryCustomer
集合可能值得详细说明。是的,但这取决于OP,除了OP发布的内容之外,我对此一无所知……并非所有情况下都如此。例如,someList.stream.forEach()可能有副作用。“地图、过滤器等不应该。”SamwellTarly表示感谢,并补充道,但foreach是一种终端操作,其目的是产生副作用,而过滤器则不是。@Nicktar使用上述代码时,我必须考虑很多情况。假设每个客户可能有5到300个补充客户。辅助客户对象位于客户对象内部。当我们从表中查询客户时,我们查询整个客户。(按辅助客户查询)。