top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to remove duplicates from ArrayList in Java?

0 votes
385 views
How to remove duplicates from ArrayList in Java?
posted Nov 15, 2017 by Frank Lee

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

To remove dupliates from ArrayList, we can convert it into Set. Since Set doesn't contain duplicate elements, it will have only unique elements.

Let's see an example to remove duplicates from ArrayList:

public class RemoveDuplicateArrayList {   
    public static void main(String[] args) {  
        List<String> l = new ArrayList<String>();  
        l.add("Mango");  
        l.add("Banana");  
        l.add("Mango");  
        l.add("Apple");  
        System.out.println(l.toString());  
        Set<String> s = new LinkedHashSet<String>(l);  
        System.out.println(s);  
    }  
}  

Output:

Before converting to set
[Mango, Banana, Mango, Apple]
After converting to set
[Mango, Banana, Apple]

answer Nov 17, 2017 by Ammy Jack
...