java - 使用过滤器将java for循环转换为流
问题描述
我已将常规 for 循环代码转换为 java 8 流。我尝试了一些,但我仍在学习这个并且没有想法,请提出想法。这可以进一步简化吗?除了使用 forEach 之外,我无法改变太多。另外,为什么我必须在 getERecordFromId((String)eid) 中将 eid 类型转换为 String
Stream <String>eIdsStream = getEidStream();
final HashSet<String> declinedRecords = new HashSet<>();
eIdsStream.forEach (eid -> {
ERecord eRecord = getERecordFromId((String)eid);
if(eRecord.getEHash() != null && Status.DECLINED == eRecord.getStatus()) {
declineRecords.add(eRecord.getEHash());
}
}
解决方案
由于您使用原始Stream
变量,因此需要进行强制转换。假设getEidStream()
返回 a Stream<String>
,您应该将其分配给Stream<String>
变量,或者根本不将其分配给变量。
using首先forEach
破坏了使用Stream
s 的目的。
您应该使用filter
andmap
来转换Stream
以保存所需的元素,然后收集到Set
.
Set<String> declinedRecords =
getEidStream().map(eid -> getERecordFromId(eid))
.filter(eRecord -> eRecord.getEHash() != null && Status.DECLINED == eRecord.getStatus())
.map(ERecord::getEHash)
.collect(Collectors.toSet());
推荐阅读
- c# - 点击下一页后过滤搜索重置浏览量
- c++ - 更改具有项目列表作为值的 Map 数据结构中配对项目的值
- python - UnicodeDecodeError:“utf-8”编解码器无法解码位置 71 中的字节 0xcd:无效的继续字节
- android - Android google登录:添加配置json文件
- sql-server - 当 IF 条件为真时,SQL ELSE 块仍然抛出错误
- django - 当产品只是属性类中的外键时,如何创建产品过滤器?(Django电子商务)
- redirect - pfsense:捕获公共 IP 的流量并重定向到本地网络
- javascript - 从数组中查找子字符串,然后在 javascript 中将其删除
- excel - Excel VBA .Filter 在过滤器字符串中使用单引号访问记录集
- git - 无法使用 vscode 和 docker 进行 git pull 或 commit