检查Set中是否存在java对象

时间:2015-10-29 06:22:09

标签: java set java-8

我有Set,我会检查具有相同属性的Object是否仍然存在。我的第一种方法是迭代列表并检查,但我想在Java 8中有更好的方法。有没有人有任何建议如何以优雅的方式检查这个?

final Set<UserSelected> preparedUserSelected = new HashSet<>();

    UserSelected userSelected1 = new UserSelected();
    userSelected1.setInstitutionId("1");
    userSelected1.setUserId("1");
    userSelected1.setChatMessageFilter(ChatMessageFilterEnum.TYP2);

    UserSelected userSelected2 = new UserSelected();
    userSelected2.setInstitutionId("2");
    userSelected2.setUserId("2");
    userSelected2.setChatMessageFilter(ChatMessageFilterEnum.TYP1);

    UserSelected userSelected3 = new UserSelected();
    userSelected3.setInstitutionId("3");
    userSelected3.setUserId("3");
    userSelected3.setChatMessageFilter(ChatMessageFilterEnum.TYP2);

    preparedUserSelected.add(userSelected1);
    preparedUserSelected.add(userSelected2);
    preparedUserSelected.add(userSelected3);

    UserSelected userSelectedToCheck = new UserSelected();
    userSelectedToCheck.setInstitutionId("2");
    userSelectedToCheck.setUserId("2");
    userSelectedToCheck.setChatMessageFilter(ChatMessageFilterEnum.TYP1);

    boolean contains = false;
    for (final UserSelected userSelected : preparedUserSelected) {
        if (userSelectedToCheck.getInstitutionId().equals(userSelected.getInstitutionId())
            && userSelectedToCheck.getUserId().equals(userSelected.getUserId())
            && userSelectedToCheck.getChatMessageFilter() == userSelected.getChatMessageFilter())
            contains = true;
    }

    System.out.println("contains: " + contains);

2 个答案:

答案 0 :(得分:2)

您需要在equals课程中正确实施hashCodeUserSelected方法。之后,您可以使用preparedUserSelected.contains(userSelectedToCheck)轻松检查是否存在。

以下为您的班级equals/hashCode的示例实施:

@Override
public int hashCode() {
    return Objects.hash(getUserId(), getInstitutionId(), getChatMessageFilter());
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null || getClass() != obj.getClass())
        return false;
    UserSelected other = (UserSelected) obj;
    return Objects.equals(getChatMessageFilter(), other.getChatMessageFilter()) &&
            Objects.equals(getInstitutionId(), other.getInstitutionId()) &&
            Objects.equals(getChatMessageFilter(), other.getChatMessageFilter());
}

答案 1 :(得分:0)

试试这个anyMatch Lambda Expression(Java 8)。

  

返回此流的任何元素是否与提供的谓词匹配。如果不是确定结果所必需的,则不能评估所有元素的谓词。如果流为空,则返回false并且不评估谓词。

boolean isExist = preparedUserSelected.stream()
            .anyMatch(userSelected -> userSelected.getInstitutionId().equalsuserSelected.getInstitutionId());