Remove Duplicate in ArrayList using Comparator in TreeSet



public class StudentRemoveDuplicates {

    public static void main(String[] args) {
        List list1 = new ArrayList();
        list1.add(new Student("Amit", "100"));
        list1.add(new Student("Anindita", "101"));
        list1.add(new Student("Abcd", "102"));
        list1.add(new Student("Xyz", "103"));

        List list2 = new ArrayList();
        list2.add(new Student("Abcd", "102"));
        list2.add(new Student("Xyz", "104"));

        list1.addAll(list2);

        System.out.println("\n***** Merging 2 lists with duplicates *******\n");
        System.out.println(list1);

        Set setOfStudents = new TreeSet<>(new Comparator() {

            @Override
            public int compare(Student o1, Student o2) {
                if (o1.getId().equalsIgnoreCase(o2.getId())) {
                    return 0;
                }
                return 1;
            }
        });
       
        setOfStudents.addAll(list1);

       
        System.out.println("\n***** After removing duplicates *******\n");
        final ArrayList newList = new ArrayList(setOfStudents);
        System.out.println(newList);
    }
}


 Output

***** Merging 2 lists with duplicates *******

[
Name=Amit   Id=100,
Name=Anindita   Id=101,
Name=Abcd   Id=102,
Name=Xyz   Id=103,
Name=Abcd   Id=102,
Name=Xyz   Id=104]

***** After removing duplicates *******

[
Name=Amit   Id=100,
Name=Anindita   Id=101,
Name=Abcd   Id=102,
Name=Xyz   Id=103,
Name=Xyz   Id=104]

 

0 comments: