【Java用法】java 8两个List集合取交集、并集、差集、去重并集
程序员文章站
2022-03-10 21:55:08
在业务的开发过程中会经常用到两个List集合相互取值的情况,于是记录在此,方便后续使用哦~~~public class ListTest { public static void main(String[] args) { ArrayList listA = CollectionUtil.toList("a", "b", "c", "d", "e"); ArrayList listB = Collect...
在业务的开发过程中会经常用到两个List集合相互取值的情况,于是记录在此,方便后续使用哦~~~
public class ListTest {
public static void main(String[] args) {
ArrayList<String> listA = CollectionUtil.toList("a", "b", "c", "d", "e");
ArrayList<String> listB = CollectionUtil.toList( "b", "c", "d", "e", "f");
System.out.println("listA = " + listA);
System.out.println("listB = " + listB);
// listA和listB的差集(listA - listB)
List<String> collect = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());
System.out.println("listA - listB的差集 = " + collect);
// listA和listB的差集(listB - listA)
List<String> collect1 = listB.stream().filter(item -> !listA.contains(item)).collect(Collectors.toList());
System.out.println("listB - listA的差集 = " + collect1);
// listA和listB交集
List<String> 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<String> distinctList = listA.stream().distinct().collect(Collectors.toList());
System.out.println("listA和listB去重并集 = " + distinctList);
}
}
运行结果为:
完结!
本文地址:https://blog.csdn.net/weixin_44299027/article/details/112841905
下一篇: 线程通知和等待