代码之家  ›  专栏  ›  技术社区  ›  J. Doe

是否有任何Java内置方法可以将2个int的组合组合起来?

  •  2
  • J. Doe  · 技术社区  · 7 年前

    这是我的代码:

    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);
        }
    }
    

    我在一个对象列表中循环,我想通过以下方式获得唯一的:

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

    我想知道Java中是否有内置类/方法。我查过字典和MultiMapValues,但有点粗糙。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Naman    7 年前

    您只需按照以下方式进行操作:

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

    hashCode equals

    如果你只是想 List 你可以使用 Stream.distinct 作为:

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