简体   繁体   中英

Compare two list in java

I have two list :

list1 = [1,2,3]
list2 = [2,3,4] 

I want to take all the element of two list with no same value and each element will repeat once example :

list3 = [1,2,3,4]

list3 will get element of list1 and list2 .

The quick way is to use a Set for example :

Input

List<Integer> list1 = Arrays.asList(1,2,3);

List<Integer> list2 = Arrays.asList(2,3,4);

Add your lists to Set

Set<Integer> set = new TreeSet<>();
set.addAll(list1);        
set.addAll(list2);

Output

[1, 2, 3, 4]
for(Integer i : list2){
    if(!list1.contains(i)){
        list1.add(i);
    }
}

Add the unique values from the 2nd list to the first one:

for (int i = 0; i < list2.size(); i++)
    if (!list1.contains(list2.get(i))
        list1.add(list2.get(i));

You can do this properly with :

List<Integer> A = Arrays.asList(1, 2, 3);
List<Integer> B = Arrays.asList(2,3,4);

List<Integer> D = ListUtils.subtract(B, A);// contain 4

Output

List<Integer> C = ListUtils.union(A, D); // 1,2,3,4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM