IT이야기

두 세트 간의 차이점 확인

cyworld 2022. 5. 22. 11:26
반응형

두 세트 간의 차이점 확인

그래서 만약 내가 두 세트를 가지고 있다면:

Set<Integer> test1 = new HashSet<Integer>();
test1.add(1);
test1.add(2);
test1.add(3);

Set<Integer> test2 = new HashSet<Integer>();
test2.add(1);
test2.add(2);
test2.add(3);
test2.add(4);
test2.add(5);

비교해서 4개, 5개 세트만 돌려받을 수 있는 방법은 없을까?

이것을 사용해 보십시오.

test2.removeAll(test1);

Set#removeAll

이 집합에서 지정된 집합에 포함된 모든 요소 제거(선택적 작업)지정된 집합도 집합인 경우, 이 연산은 이 집합의 값이 두 집합의 비대칭 설정 차이가 되도록 효과적으로 수정한다.

Guava(구 구글 컬렉션) 라이브러리를 사용하는 경우 다음과 같은 해결책이 있다.

SetView<Number> difference = com.google.common.collect.Sets.difference(test2, test1);

돌아온 사람들SetViewa이다Set이것은 당신이 불변하거나 다른 세트로 복사할 수 있는 실시간 표현이다. test1그리고test2그대로 남아 있다.

예:

test2.removeAll(test1)

비록 이것이 변이되겠지만test2보존해야 할 경우 복사본을 만드십시오.

또한, 당신은 아마도 말했을 것이다.<Integer>대신에<int>.

자바 8

우리는 다음과 같이 효용 방법을 쓰는데 술어가 필요한 removeIf를 사용할 수 있다.

// computes the difference without modifying the sets
public static <T> Set<T> differenceJava8(final Set<T> setOne, final Set<T> setTwo) {
     Set<T> result = new HashSet<T>(setOne);
     result.removeIf(setTwo::contains);
     return result;
}

그리고 아직 이전 버전에 있는 경우 removeAll을 다음과 같이 사용할 수 있다.

public static <T> Set<T> difference(final Set<T> setOne, final Set<T> setTwo) {
     Set<T> result = new HashSet<T>(setOne);
     result.removeAll(setTwo);
     return result;
}

Apache Commons를 사용할 수 있음CollectionUtils.disjunction모든 차이점을 알아내기 위해CollectionUtils.subtract첫 번째 컬렉션에서 차액을 얻기 위해.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

이를 수행하는 방법의 예는 다음과 같다.

import org.apache.commons.collections4.CollectionUtils;
import java.util.List;

var collection1 = List.of(-1, 0, 1, 2, 3, 4, 5);
var collection2 = List.of(       1, 2, 3, 4, 5, 6, 7, 8, 9);

// [-1, 0, 1, 2, 3, 4, 5]
System.out.println(collection1);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println(collection2);

// [-1, 0]
System.out.println(CollectionUtils.subtract(collection1, collection2));
// [6, 7, 8, 9]
System.out.println(CollectionUtils.subtract(collection2, collection1));

// [1, 2, 3, 4, 5]
System.out.println(CollectionUtils.retainAll(collection1, collection2));
// [1, 2, 3, 4, 5]
System.out.println(CollectionUtils.retainAll(collection2, collection1));

// [-1, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9]
System.out.println(CollectionUtils.collate(collection1, collection2));
// [-1, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9]
System.out.println(CollectionUtils.collate(collection2, collection1));

// [-1, 0, 6, 7, 8, 9]
System.out.println(CollectionUtils.disjunction(collection1, collection2));
// [-1, 0, 6, 7, 8, 9]
System.out.println(CollectionUtils.disjunction(collection2, collection1));

// [1, 2, 3, 4, 5]
System.out.println(CollectionUtils.intersection(collection1, collection2));
// [1, 2, 3, 4, 5]
System.out.println(CollectionUtils.intersection(collection2, collection1));

// [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println(CollectionUtils.union(collection1, collection2));
// [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println(CollectionUtils.union(collection2, collection1));

최근에 내가 직접 사용했지만 여기서 언급되지 않은 해결책을 추가했다.Apache Commons Collections를 사용할 수 있는 경우SetUtils#difference방법:

// Returns all the elements of test2 which are not in test1
SetUtils.difference(test2, test1) 

문서에 따르면 반환된 세트는 수정할 수 없는 보기입니다.

\ b(또는 a - b)로 표시된 주어진 집합의 차이를 포함하는 수정할 수 없는 보기를 반환한다.반환된 보기는 b의 구성원이 아닌 의 모든 요소를 포함한다.

전체 설명서: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/SetUtils.html#difference-java.util.Set-java.util.Set-

여기에 한 가지 예를 들면 다음과 같다(시스템이 안에 있음).existingState, 그리고 제거할 요소들을 찾기를 원한다 (에 없는 요소들newState에 존재하지만existingState추가할 요소(에 있는 항목) 및 추가 요소newState그러나 에 있지 않다.existingState) :

public class AddAndRemove {

  static Set<Integer> existingState = Set.of(1,2,3,4,5);
  static Set<Integer> newState = Set.of(0,5,2,11,3,99);

  public static void main(String[] args) {

    Set<Integer> add = new HashSet<>(newState);
    add.removeAll(existingState);

    System.out.println("Elements to add : " + add);

    Set<Integer> remove = new HashSet<>(existingState);
    remove.removeAll(newState);

    System.out.println("Elements to remove : " + remove);

  }
}

그 결과로 다음과 같은 결과를 산출할 수 있다.

Elements to add : [0, 99, 11]
Elements to remove : [1, 4]

Java 8을 사용하는 경우 다음과 같은 작업을 시도해 보십시오.

public Set<Number> difference(final Set<Number> set1, final Set<Number> set2){
    final Set<Number> larger = set1.size() > set2.size() ? set1 : set2;
    final Set<Number> smaller = larger.equals(set1) ? set2 : set1;
    return larger.stream().filter(n -> !smaller.contains(n)).collect(Collectors.toSet());
}

.addAll()과 .retainAll()을 사용하여 교차로를 만들고 .removeIf()를 사용하여 교차로(또는 중복 요소)를 조합에서 제거할 수 있다.

HashSet union = new HashSet(group1);
union.addAll(group2);
        
System.out.println("Union: " + union);
        
HashSet intersection = new HashSet(group1);
intersection.retainAll(group2);
        
System.out.println("Intersection: " + intersection);
        
HashSet difference = new HashSet(union);
difference.removeIf(n -> (difference.contains(intersection)));
        
System.out.println("Difference: " + difference);

순서는 중요한데, 4와 5는 (정수가 아닌) 인트(Unt)가 필요하기 때문이다.test2.removeAll(test1).

참조URL: https://stackoverflow.com/questions/18644579/getting-the-difference-between-two-sets

반응형