Cannot make filter-gt;forEach-gt;collect in one stream?(无法在一个流中制作过滤器-forEach-collect?)
问题描述
我想实现这样的目标:
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:
无法在原始类型 void 上调用 collect(Collectors.toList()).
Cannot invoke
collect(Collectors.toList())on the primitive typevoid.
我需要 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 是一种返回原始对象副本的方法,包括提供的更改.
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->collect?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法在一个流中制作过滤器->forEach->collect?
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
