JAVA集合快速取交集方法
在实际业务开发中,遇见集合取交集、差集的数据,每个集合几十万条左右数据,利用传统方式取效率低的可怕,在网上找过很多的方法,无意中看到Guava,是谷歌出的一个工具类,经过验证,效率高的让人意想不到。
项目集成
pom文件
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
项目实例
List<String> personList = new ArrayList<>();
List<String> personOldList = new ArrayList<>();
Set person = new HashSet<>(personList);
Set personOld = new HashSet<>(personOldList);
//取差集
Set<String> result3 = Sets.difference(person, personOld);
System.out.println(result3.size());
//取交集
Set<String> result4 = Sets.intersection(person, personOld);
System.out.println(result4.size());
源码
有很多实用的方法,有兴趣的可以自己查阅了。
@java.lang.Deprecated
public static <E> java.util.Set<E> newSetFromMap(java.util.Map<E,java.lang.Boolean> map) { /* compiled code */ }
public static <E> com.google.common.collect.Sets.SetView<E> union(java.util.Set<? extends E> set1, java.util.Set<? extends E> set2) { /* compiled code */ }
public static <E> com.google.common.collect.Sets.SetView<E> intersection(java.util.Set<E> set1, java.util.Set<?> set2) { /* compiled code */ }
public static <E> com.google.common.collect.Sets.SetView<E> difference(java.util.Set<E> set1, java.util.Set<?> set2) { /* compiled code */ }
public static <E> com.google.common.collect.Sets.SetView<E> symmetricDifference(java.util.Set<? extends E> set1, java.util.Set<? extends E> set2) { /* compiled code */ }