Java 2 List collection data summation and complement operations

During the development process, we may need to process the data in 2 or more List collections. For example, the data of multiple List collections obtains the same element, and the data of multiple List collections obtains data that only belongs to itself, as shown in the figure:

write picture description here

 

 

Here are 2 Lists introduced, there are some business requirements that we can deal with the 3 cases on the figure
* Only belong to A
* Common elements
* Only belong to B

This processing method is not unfamiliar in mathematics, it only belongs to A, which is equivalent to the relative complement of B on A on the set; the same element, the union of A and B; only belongs to B, which is equivalent to the relative complement of A on B on the set Relative complement. Understand these concepts, let's introduce how to implement Java code, the code is as follows

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("Union of A and B: " + C);

    B.removeAll(C);
    System.out.println("A relative complement of B: " + B);

    A.removeAll(C);
    System.out.println("B's relative complement of A: " + A);

  }

  The result of running it:

 

Body: https://blog.csdn.net/gnf_cc/article/details/71214126

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249410&siteId=291194637