首页 > 解决方案 > 使用过滤器将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());
        }
    }

标签: javalambdajava-stream

解决方案


由于您使用原始Stream变量,因此需要进行强制转换。假设getEidStream()返回 a Stream<String>,您应该将其分配给Stream<String>变量,或者根本不将其分配给变量。

using首先forEach破坏了使用Streams 的目的。

您应该使用filterandmap来转换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());

推荐阅读