Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from an ArrayList?

How to remove duplicates from an ArrayList?

I have getCcnptags array as [java,php,c++,c,java,php] which i am getting from bean array, and I am giving hyper link to each array variable, but I want to remove duplicates before adding hyper link to it, does it possible to add any code in my below code to remove duplicates.

for(int k=0;k<name.getCcnptags().size();k++)
    {

    String tag=name.getCcnptags().get(k);
        if(k!=name.getCcnptags().size()-1)
    {
    tag=tag+",";

    }
    %>
    <a href='#'><%=tag%></a>
}
like image 607
user2545106 Avatar asked Jul 24 '26 14:07

user2545106


2 Answers

Better use a HashSet. If not possible then you can use a temporary HashSet for this.

ArrayList a= new ArrayList();
HashSet hs = new HashSet();
hs.addAll(a);  // willl not add the duplicate values
a.clear();
a.addAll(hs);  // copy the unique values again to arraylist
like image 136
stinepike Avatar answered Jul 26 '26 02:07

stinepike


Use Set interace,A collection that contains no duplicate elements.

From ArrayList create Hashset and use it.

Collection object has a constructor that accept a Collection object to initial the value.

ArrayList yourlist= new ArrayList();
HashSet nodupesSet= new HashSet(yourlist);

Now iterate over nodupesSet

like image 28
Suresh Atta Avatar answered Jul 26 '26 04:07

Suresh Atta