兩個List集合取交集、並集、差集


  list1.removeAll(list2):從list1中移除存在list2中的元素。
  調用流程:removeAll->contains->equals方法,對於引用類型,要使用removeAll,需要重寫equals方法

  removeAll源碼:

public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
}

  contains源碼

public boolean contains(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
}

  當對象o不為空時,迭代判斷用到了Object的equals方法,而Object的equals方法指的是兩個對象的引用是否相等,如果我們要判斷兩個對象的內容相等,這里就需要重寫equals方法。

  JDK1.8 lambda表達式取交集、並集、差集(String類型,已重寫了equals方法)

public static void main(String[] args) {
    List<String> list1 = new ArrayList<String>();
    list1.add("1");
    list1.add("2");
    list1.add("3");
    list1.add("5");
    list1.add("6");
 
    List<String> list2 = new ArrayList<String>();
    list2.add("2");
    list2.add("3");
    list2.add("7");
    list2.add("8");
 
    // 交集
    List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
    System.out.println("---交集 intersection---");
    intersection.parallelStream().forEach(System.out :: println);
 
    // 差集 (list1 - list2)
    List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
    System.out.println("---差集 reduce1 (list1 - list2)---");
    reduce1.parallelStream().forEach(System.out :: println);

// 並集 List<String> listAll = list1.parallelStream().collect(toList()); List<String> listAll2 = list2.parallelStream().collect(toList()); listAll.addAll(listAll2); System.out.println("---並集 listAll---"); listAll.parallelStream().forEachOrdered(System.out :: println); // 去重並集 List<String> listAllDistinct = listAll.stream().distinct().collect(toList()); System.out.println("---得到去重並集 listAllDistinct---"); listAllDistinct.parallelStream().forEachOrdered(System.out :: println); System.out.println("---原來的List1---"); list1.parallelStream().forEachOrdered(System.out :: println); System.out.println("---原來的List2---"); list2.parallelStream().forEachOrdered(System.out :: println); }

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM