Java 2 個 List 集合資料求並、補集操作

來源:互聯網
上載者:User

標籤:rem   retain   tail   class   info   List 集合   alt   remove   圖片   

開發過程中,我們可能需要對 2 個 或多個 List 集合中的資料進行處理,比如多個 List 集合資料求 相同元素,多個 List 集合資料得到只屬於本身的資料,示:

這裡寫圖片描述

 

 

這裡以 2 個 List 介紹,有一些業務要求我們處理得到圖上的 3 中情況
* 只屬於 A
* 共同的元素
* 只屬於 B

這種處理方式在數學上並不陌生,只屬於 A ,相當於集合上 B 關於 A 的相對補集;相同的元素,A 和 B 的並集;只屬於 B ,相當於集合上 A 關於 B 的相對補集。明白了這幾個概念,下面我們就介紹 Java 代碼該如何為實現,代碼如下

public static void test() {    List<Integer> A = new ArrayList<Integer>();    A.add(1);    A.add(2);    A.add(3);    A.add(4);    List<Integer> B = new ArrayList<Integer>();    B.add(2);    B.add(4);    B.add(5);    B.add(6);    Collection C = new ArrayList<Integer>(A);    C.retainAll(B);    System.out.println("A 與 B 並集:" + C);    B.removeAll(C);    System.out.println("A 關於 B 的相對補集:" + B);    A.removeAll(C);    System.out.println("B 關於 A 的相對補集:" + A);  }

  運行得到的結果:

 

本文引自:71214126

 

Java 2 個 List 集合資料求並、補集操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.