Java流式处理:优化保护组过滤与信息构建

在处理保护组相关的操作时,我们常常需要根据特定条件过滤保护组,并构建相关的信息列表。本文将介绍如何使用Java流式处理来优化这段代码逻辑,使其更简洁高效。

原始代码

以下是原始代码片段,它从一个保护组列表中筛选出与指定终端点相关的保护组,并为每个相关的保护组构建配置信息列表:javaList relatedPgList = protectionGroupList.stream() .filter(r -> r.getPrs().stream().map(ProtectionRelation::getWorkUnits).flatMap(unitList -> unitList.stream().map(u -> u.getObjName().getName())).anyMatch(endTps::contains) || r.getPrs().stream().map(ProtectionRelation::getProtectUnits).flatMap(unitList -> unitList.stream().map(u -> u.getObjName().getName())).anyMatch(endTps::contains)) .collect(Collectors.toList());

    relatedPgList.forEach(pg -> {            if (otnFc.getPgInfos() == null || otnFc.getPgInfos().stream().noneMatch(protectionGroupInfo -> protectionGroupInfo.getPgIdAndLabel().getUuid().equals(pg.getPgId()))) {                OtnProtectionGroupInfo singlePgInfo = DataUtils.getSinglePgLabel(pg.getMeuuid(), pg.getPgId());                singelCfgInfoList.add(DataUtils.buildPgCfgInfoList(pg.getPgId(), singlePgInfo));            }        });

这段代码逻辑比较复杂,可读性较差。

优化后的代码

我们可以使用Java流式处理来简化代码逻辑,使其更清晰易读:javaList relatedPgList = protectionGroupList.stream() .filter(r -> r.getPrs().stream() .flatMap(pr -> Stream.concat( pr.getWorkUnits().stream().map(u -> u.getObjName().getName()), pr.getProtectUnits().stream().map(u -> u.getObjName().getName())))) .anyMatch(endTps::contains)) .collect(Collectors.toList());

relatedPgList.forEach(pg -> { if (otnFc.getPgInfos() == null || otnFc.getPgInfos().stream() .noneMatch(protectionGroupInfo -> protectionGroupInfo.getPgIdAndLabel().getUuid().equals(pg.getPgId()))) { OtnProtectionGroupInfo singlePgInfo = DataUtils.getSinglePgLabel(pg.getMeuuid(), pg.getPgId()); singelCfgInfoList.add(DataUtils.buildPgCfgInfoList(pg.getPgId(), singlePgInfo)); }});

优化后的代码使用了 flatMap 操作将工作单元和保护单元的名称流合并,并使用 anyMatch 操作判断是否存在与指定终端点匹配的名称。

总结

通过使用Java流式处理,我们可以有效地简化代码逻辑,提高代码的可读性和效率。在处理集合数据时,我们应该优先考虑使用流式处理来优化代码。

Java流式处理:优化保护组过滤与信息构建

原文地址: https://www.cveoy.top/t/topic/cUIU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录