检查嵌套循环上的条件添加到列表,java 8

时间:2017-11-24 09:30:16

标签: java java-8

下面我有两个清单。在循环这两个列表时,我需要检查一个条件添加到一个元素。

List<EcStgClientRolesRecipients> ecStgRoleList = new ArrayList<>();

for (EcStgClientRolesRecipients ecStgClientRolesRecipients : ecStgClientRolesRecipientList) {
    for (EcStgClientRoles ecStgClientRole : ecStgClientRoleList) {
        if (ecStgClientRole.getRoleId().equals(ecStgClientRolesRecipients.getRoleId())) {                        
            ecStgClientRolesRecipients.setEcStgClientRoles(ecStgClientRole);
            ecStgRoleList.add(ecStgClientRolesRecipients);
        }
     }
     break;
}

return ecStgRoleList;

我试图将其转换为Java 8代码,但它无法正常工作。我错过了什么?

List<EcStgClientRolesRecipients> filtedRoleRecipients = new ArrayList<>();  

Predicate<EcStgClientRolesRecipients> roleRecipientCheck =
    recipient -> ecStgClientRoleList.stream()
        .anyMatch(ecStgClientRole ->  recipient.getRoleId() == ecStgClientRole.getRoleId());

filtedRoleRecipients = ecStgClientRolesRecipientList.stream()
              .filter(roleRecipientCheck)
              .collect(Collectors.toList());

1 个答案:

答案 0 :(得分:2)

我可以这样想,但它比简单的for循环更难以理解:

ecStgClientRolesRecipientList.stream()
            .map(x -> new AbstractMap.SimpleEntry<>(
                    ecStgClientRoleList.stream().filter(y -> x.getRoleId().equals(y.getRoleId())).findAny(), x))
            .filter(pair -> pair.getKey().isPresent())
            .map(pair -> {
                EcStgClientRolesRecipients e = pair.getValue();
                e.setEcStgClientRoles(pair.getKey().get());
                return e;
            })
            .collect(Collectors.toList());