本文简单介绍下计算集合对称差的几种方法。java
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>22.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency>
两个集合的对称差是只属于其中一个集合,而不属于另外一个集合的元素组成的集合。
集合A和B的对称差一般表示为AΔB,对称差的符号在有些图论书籍中也使用符号⊕来表示。例如:集合{1,2,3}和{3,4}的对称差为{1,2,4}。apache
在guava里头是用symmetricDifference方法segmentfault
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3, 4)); Set<Integer> b = new HashSet<>(Arrays.asList(3, 4, 5, 6)); Sets.SetView<Integer> result = Sets.symmetricDifference(a,b); System.out.println(result);
在collection4里头是用disjunction方法maven
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5)); Set<Integer> b = new HashSet<>(Arrays.asList(1, 2, 3)); SetUtils.SetView<Integer> result = SetUtils.disjunction(a, b); assertTrue(result.toSet().contains(5) && result.toSet().contains(3));
上述的两个方法都不能标注哪些元素属于第一个集合,哪一个属于第二个集合,有时候咱们又想获取对称差的时候顺便可以计算出哪一个元素属于哪一个集合,这个时候怎么办呢,能够模仿collection4中的方法来获取:google
public static <O> Pair<Collection<O>,Collection<O>> disjunction2(final Collection<? extends O> first, final Collection<? extends O> second, final Predicate<O> p) { final List<O> firstList = first.stream() .filter(e -> p.evaluate(e)) .collect(Collectors.toList()); final List<O> secondList = second.stream() .filter(e -> !firstList.remove(e)) .collect(Collectors.toList()); return Pair.of(firstList,secondList); }
实例lua
final List<String> first = Arrays.asList("bbb", "ccc","dddd","aaa"); final List<String> second = Arrays.asList("aaa", "zzz", "ccc"); System.out.println(disjunction(first,second,TruePredicate.truePredicate()));
输出code
([bbb, dddd],[zzz])