I have multiple Integer ArrayList, which contains some duplicate elements. I want to get the unique elements from them. But how?
java.util.ArrayList.removeAll() is not serving my purpose completely. See the below test code-
ArrayList<Integer> d = new ArrayList<Integer>();
d.add(2);
d.add(4);
d.add(5);
d.add(7);
d.add(8);
d.add(9);
ArrayList<Integer> e = new ArrayList<Integer>();
e.add(3);
e.add(7);
d.removeAll(e);
for (int t : d) {
System.out.print(t+", ");
}
In output, i am getting 2, 4, 5, 8, 9, . Clearly 3 is missing. Also just to keep it simple, I am using only two ArrayList here but in my code, i have more than two ArrayList.
How I can find unique elements in multiple ArrayList in Java
Create a
Set<Integer>from yourList<Integer>. The set will contain no duplicate objects:Note that you can add more
List<Integer>in theSetby using theSet#addAllmethod (as shown in rahulroc answer) to add more integers in your not duplicated elements collection:Also, as best practice, try to program to interfaces (List, Set, etc), not to class implementations (ArrayList, HashSet), as shown here: What does it mean to “program to an interface”?