2 ArrayList - Remove duplicates without using Set


First remove duplicates:
      arrayList1.removeAll(arrayList2);
Then merge two arrayList:
      arrayList1.addAll(arrayList2);
Lastly, sort your arrayList if you wish:
       collections.sort(arrayList1);
 

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListDuplicates {

    public static void main(String[] args) {
        List list1 = new ArrayList();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
       
        List list2 = new ArrayList();
        list2.add(1);
        list2.add(2);
        list2.add(5);
        list2.add(6);
       
        System.out.println("Remove duplicates from list1 by calling removeAll");
        list1.removeAll(list2);
        System.out.println("After removeAll is called " + list1);
       
        System.out.println("Merge the 2 lists");
        list1.addAll(list2);
        System.out.println("After Merge "+ list1);
       
        System.out.println("Sorting");
        Collections.sort(list1);
        System.out.println("Final after Sort "+ list1);
       

    }
 

Output
Remove duplicates from list1 by calling removeAll
After removeAll is called [3, 4]
Merge the 2 lists
After Merge [3, 4, 1, 2, 5, 6]
Sorting
Final after Sort [1, 2, 3, 4, 5, 6]

0 comments: