java core
List와 Set의 교집합(intersection) 구하기
'김용환'
2016. 4. 12. 18:51
Guava에서는 Set의 교집합(intersection)을 지원한다. 하지만, List쪽은 지원하지 않는다.
http://guava-libraries.googlecode.com/svn/tags/release04/javadoc/com/google/common/collect/Sets.html
static <E> Sets.SetView<E> intersection(Set<E> set1, Set<?> set2)
참고
여러 List 간 교집합을 간단히 구하려면, java.util.List의 retainAll() 메소드를 사용하면 교집합을 얻을 수 있다.
@Test
public void retainTest() {
List<Integer> l1 = Lists.newArrayList(1, 2, 3);
List<Integer> l2 = Lists.newArrayList(3, 4, 5);
l1.retainAll(l2);
System.out.println(l1);
l2.retainAll(l1);
System.out.println(l2);
assertEquals(l1, l2);
}
결과
3