I have a list that contain elements, I want to remove the duplicates. I have tried to do that but it didn’t work.
This is the code :
//list is the original list containing duplicates
Iterator it1=list.iterator();//iterator1
while (it1.hasNext())
{
Iterator it2=list.iterator(); //iterator2
if(it1.next().equals(it2.next()))
{
//liststeps is the list without duplicates
liststeps.add(it1.next());
}
}
System.out.println("multiple list "+list.toString());
System.out.println("list "+liststeps.toString());
Results:
multiple list [Open, In Progress, Waiting Customer Test, Closed, Open, Step11, Step22, Open, In Progress, Waiting Customer Test, Closed]
list [In Progress, Step11, In Progress]
Simply construct a
HashSetor aTreeSetfrom your list:This will remove the duplicates, but will likely re-order the elements. If you want to preserve the order in which the (unique) elements appear in the original list, use
LinkedHashSet:Lastly, if you need the output to be a list, convert the set to a list like so: