在业务的开发过程中会经常用到两个List集合相互取值的情况,于是记录在此,方便后续使用哦~~~
public class ListTest {
public static void main(String[] args) {
ArrayList listA = CollectionUtil.toList("a", "b", "c", "d", "e");
ArrayList listB = CollectionUtil.toList( "b", "c", "d", "e", "f");
System.out.println("listA = " + listA);
System.out.println("listB = " + listB);
// listA和listB的差集(listA - listB)
List collect = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());
System.out.println("listA - listB的差集 = " + collect);
// listA和listB的差集(listB - listA)
List collect1 = listB.stream().filter(item -> !listA.contains(item)).collect(Collectors.toList());
System.out.println("listB - listA的差集 = " + collect1);
// listA和listB交集
List intersection = listA.stream().filter(listB::contains).collect(Collectors.toList());
System.out.println("listA和listB交集 = " + intersection);
// listA和listB并集(不去重)
listA.addAll(listB);
System.out.println("listA和listB并集 = " + listA);
// listA和listB并集(去重)
List distinctList = listA.stream().distinct().collect(Collectors.toList());
System.out.println("listA和listB去重并集 = " + distinctList);
}
}
运行结果为:
完结!
本文地址:https://blog.csdn.net/weixin_44299027/article/details/112841905
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!