在业务的开发过程中会经常用到两个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); } }
运行结果为:
完结!