This example shows how to remove duplicate from ArrayList using Comparator. The easiest way to remove duplicate is by passing the List to an Set. We will use Comparator to remove duplicate elements. Once you have the Set you can again pass it back to ArrayList.
import java.util.ArrayList; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class RemoveDuplicate { public static void main(String[] args) { final ArrayList students = new ArrayList(); students.add(new Student("Student1", "1000")); students.add(new Student("Student2", "1001")); students.add(new Student("Student3", "1002")); students.add(new Student("Student4", "1003")); students.add(new Student("Student5", "1001")); students.add(new Student("Student6", "1004")); /** Printing original list **/ System.out.println(students); Set set = new TreeSet(new Comparator() { @Override public int compare(Student o1, Student o2) { if(o1.getId().equalsIgnoreCase(o2.getId())){ return 0; } return 1; } }); set.addAll(students); System.out.println("\n***** After removing duplicates *******\n"); final ArrayList newList = new ArrayList(set); /** Printing original list **/ System.out.println(newList); } } class Student { private String name; private String id; public Student(String name, String id) { this.name = name; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "\n" +"Name=" + name + " Id=" + id ; } }
Output
[ Name=Student1 Id=1000, Name=Student2 Id=1001, Name=Student3 Id=1002, Name=Student4 Id=1003, Name=Student5 Id=1001, Name=Student6 Id=1004] ***** After removing duplicates ******* [ Name=Student1 Id=1000, Name=Student2 Id=1001, Name=Student3 Id=1002, Name=Student4 Id=1003, Name=Student6 Id=1004]
The above code is same as
class StudentsComparator implements Comparator {
@Override
public int compare(Student o1, Student o2) {
if(o1.getId().equalsIgnoreCase(o2.getId())){
return 0;
}
return 1;
}
}
Set set = new TreeSet(new StudentsComparator());
ohhhhhh thank you man u saved my day
works well for my android app
How to remove strings from arraylist pojo class .
How to remove duplicates strings from arraylist pojo class .
like i want to remove names from the ArrayList then how to eliminate duplicates in this.
I am also using the same one and yes it seems depend also on positioning and not guaranteed all time 🙁
There is one Problem if we add any duplicate item same as index 0 of list then that will not be removed. For ex :
students.add(new Student(“Student1”, “1000”));
students.add(new Student(“Student2”, “1001”));
students.add(new Student(“Student3”, “1002”));
students.add(new Student(“Student4”, “1000”));
Not able to figure out why so.