In this tutorial we will learn how to remove duplicates from ArrayList. The steps followed in the below example are:
1) Copying all the elements of ArrayList to LinkedHashSet. Why we choose LinkedHashSet? Because it removes duplicates and maintains the insertion order.
2) Emptying the ArrayList
3) Copying all the elements of LinkedHashSet(non-duplicate elements) to the ArrayList. Please find below the complete code.
Example: Removing duplicates from List
import java.util.ArrayList; import java.util.List; import java.util.LinkedHashSet; public class RemoveDuplicates { public static void main(String[] args) { /* Creating ArrayList of Strings and adding * elements to it */ List<String> al = new ArrayList<String>(); al.add("Ajay"); al.add("Becky"); al.add("Chaitanya"); al.add("Ajay"); al.add("Rock"); al.add("Becky"); // Displaying ArrayList elements System.out.println("Before:"); System.out.println("ArrayList contains: "+al); // Creating LinkedHashSet LinkedHashSet<String> lhs = new LinkedHashSet<String>(); /* Adding ArrayList elements to the LinkedHashSet * in order to remove the duplicate elements and * to preserve the insertion order. */ lhs.addAll(al); // Removing ArrayList elements al.clear(); // Adding LinkedHashSet elements to the ArrayList al.addAll(lhs); // Displaying ArrayList elements System.out.println("After:"); System.out.println("ArrayList contains: "+al); } }
Output:
Before: ArrayList contains: [Ajay, Becky, Chaitanya, Ajay, Rock, Becky] After: ArrayList contains: [Ajay, Becky, Chaitanya, Rock]
As you can see that the duplicates have been removed from the list and the insertion order is being preserved in the output.
Thats all we have for this tutorial. If you have any questions, feel free to ask by dropping a comment below.
How to check whether the ArrayList contains un-ordered element or not with an in-build method?
eg.
Suppose i have a strings as “ABC” and “BCA”
and if i check this ans should be true!