序
本文简单介绍下计算集合对称差的几种方法。
maven
com.google.guava
guava
22.0
org.apache.commons
commons-collections4
4.1
对称差
两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合。
集合A和B的对称差通常表示为AΔB,对称差的符号在有些图论书籍中也使用符号⊕来表示。例如:集合{1,2,3}和{3,4}的对称差为{1,2,4}。
guava
在guava里头是用symmetricDifference方法
Set a = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set b = new HashSet<>(Arrays.asList(3, 4, 5, 6));
Sets.SetView result = Sets.symmetricDifference(a,b);
System.out.println(result);
collection4
在collection4里头是用disjunction方法
Set a = new HashSet<>(Arrays.asList(1, 2, 5));
Set b = new HashSet<>(Arrays.asList(1, 2, 3));
SetUtils.SetView result = SetUtils.disjunction(a, b);
assertTrue(result.toSet().contains(5) && result.toSet().contains(3));
改进
上述的两个方法都不能标注哪些元素属于第一个集合,哪个属于第二个集合,有时候我们又想获取对称差的时候顺便能够计算出哪个元素属于哪个集合,这个时候怎么办呢,可以模仿collection4中的方法来获取:
public staticPair ,Collection > disjunction2(final Collection extends O> first, final Collection extends O> second, final Predicate p) { final List firstList = first.stream() .filter(e -> p.evaluate(e)) .collect(Collectors.toList()); final List secondList = second.stream() .filter(e -> !firstList.remove(e)) .collect(Collectors.toList()); return Pair.of(firstList,secondList); }
实例
final Listfirst = Arrays.asList("bbb", "ccc","dddd","aaa"); final List second = Arrays.asList("aaa", "zzz", "ccc"); System.out.println(disjunction(first,second,TruePredicate.truePredicate()));
输出
([bbb, dddd],[zzz])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



