无法在一个流中生成过滤器> forEach->收集? [英] Cannot make filter->forEach->collect in one stream?

查看:143
本文介绍了无法在一个流中生成过滤器> forEach->收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想达到这样的目标:

items.stream()
    .filter(s-> s.contains("B"))
    .forEach(s-> s.setState("ok"))
.collect(Collectors.toList());

过滤,然后从过滤结果中更改属性,然后将结果收集到列表中。但是,调试器说:

filter, then change a property from the filtered result, then collect the result to a list. However, the debugger says:


无法调用 collect(Collectors.toList())原始类型 void

我需要2个流吗? ?

推荐答案

forEach 旨在成为一个终端操作,是的 - 你打电话后不能做任何事情。

The forEach is designed to be a terminal operation and yes - you can't do anything after you call it.

惯用的方法是首先应用转换然后 collect()所需的数据结构。

The idiomatic way would be to apply a transformation first and then collect() everything to the desired data structure.

可以使用 map 进行转换,这是为非变异操作而设计的。

The transformation can be performed using map which is designed for non-mutating operations.

如果您正在执行非变异操作:

 items.stream()
   .filter(s -> s.contains("B"))
   .map(s -> s.withState("ok"))
   .collect(Collectors.toList());

其中 withState 是返回a的方法原始对象的副本,包括提供的更改。

where withState is a method that returns a copy of the original object including the provided change.

如果您正在执行副作用:

items.stream()
  .filter(s -> s.contains("B"))
  .collect(Collectors.toList());

items.forEach(s -> s.setState("ok"))

这篇关于无法在一个流中生成过滤器> forEach->收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆