Programing

두 세트의 교집합을 계산하는 방법은 무엇입니까?

crosscheck 2020. 5. 16. 11:12
반응형

두 세트의 교집합을 계산하는 방법은 무엇입니까? [복제]


가능한 중복 :
가변 개수의 스트링 세트의 교차점을 효율적으로 찾는

해시 셋이 두 개 있다고 가정 해보자.

Set<String> s1 = new HashSet<String>();

Set<String> s2 = new HashSet<String>();

S1 INT S2 ?

다음 retainAll()방법을 사용하십시오 Set.

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

세트를 유지하려면 교차점을 보유 세트를 작성하십시오 .

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

javadocretainAll()따르면 정확히 원하는 것입니다.

지정된 컬렉션에 포함 된이 세트의 요소 만 유지합니다 (선택적 조작). 즉, 지정된 컬렉션에 포함되지 않은 모든 요소를이 세트에서 제거합니다. 지정된 콜렉션도 세트 인 경우, 이 조작은 값이 두 세트 교집합 이되도록이 세트를 효과적으로 수정 합니다.


예이 retainAll체크 아웃

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

참고 URL : https://stackoverflow.com/questions/8882097/how-to-calculate-the-intersection-of-two-sets

반응형