简体   繁体   English

是否有Java构建方式可以将2个整数组合成一个Set?

[英]Is there any build in Java way to make a Set out of a combination of 2 ints?

This is my code: 这是我的代码:

private class UniqueClassByTwoIntProperties {
    private final int propertyOne;
    private final int propertyTwo;

    UniqueCase(final int propertyOne, final int propertyTwo) {
        this.propertyOne= propertyOne;
        this.propertyTwo= propertyTwo;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (this == obj) {
            return true;
        }

        if (!(obj instanceof UniqueCase)) {
            return false;
        }

        UniqueClassByTwoIntProperties unique = (UniqueClassByTwoIntProperties) obj;

        return unique.claimApplicationId == claimApplicationId && unique.claimCoverageId == claimCoverageId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(propertyOne, propertyTwo);
    }
}

I am looping through a list with objects, where I want to get the unique's in the following way: 我正在遍历带有对象的列表,我想通过以下方式在其中获得唯一性:

myList.stream()
      .map(row -> new UniqueClassByTwoIntProperties(row.getOne(), row.getTwo()))
      .collect(Collectors.toSet());

I was wondering if there was a build-in class/method in Java. 我想知道Java是否有内置的类/方法。 I have looked into dictionaries and MultiMapValues, but it was a bit hacky. 我研究过字典和MultiMapValues,但是有点不客气。

You can simply do it as: 您可以简单地通过以下方式进行操作:

Set<UniqueClassByTwoIntProperties> uniques = new HashSet<>(myList);

Aside : Make sure the hashCode and equals of the objects are implemented correctly for the object to be comparable. 旁白 :确保正确实现对象的hashCodeequals ,以使对象具有可比性。

If you just want the List of uniques then you can use Stream.distinct as : 如果只需要唯一List ,则可以将Stream.distinct用作:

List<UniqueClassByTwoIntProperties> uniques = myList.stream()
                                 .distinct() // for unique objects
                                 .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM