Removing duplicates and ordering a list using java
Hi everyone, in this blog post, I will be writing about 'How to remove duplicates and order a list using java'.
For removing duplicates in a list, we can put all the contents of the list to a set. For ordering the set, we can use an implementation of treeset. So in general, to remove duplicates and order a set, we could do by putting all the contents of the list to a treeset. Please refer my post about sets to understand more about treesets.
Here is the java program to remove duplicates and order a list.
For removing duplicates in a list, we can put all the contents of the list to a set. For ordering the set, we can use an implementation of treeset. So in general, to remove duplicates and order a set, we could do by putting all the contents of the list to a treeset. Please refer my post about sets to understand more about treesets.
Here is the java program to remove duplicates and order a list.
package com.blog.techjourney;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class removeDuplicatesAndOrder {
public static void main(String[] args) {
List countries = new ArrayList();
countries.add("Canada");
countries.add("Australia");
countries.add("Brazil");
countries.add("Canada");
countries.add("Egypt");
countries.add("Denmark");
System.out.println(countries);
removeDuplicatesAndOrder(countries);
System.out.println(countries);
}
public static void removeDuplicatesAndOrder(List list)
{
Set treeset = new TreeSet();
treeset.addAll(list);
list.clear();
list.addAll(treeset);
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class removeDuplicatesAndOrder {
public static void main(String[] args) {
List
countries.add("Canada");
countries.add("Australia");
countries.add("Brazil");
countries.add("Canada");
countries.add("Egypt");
countries.add("Denmark");
System.out.println(countries);
removeDuplicatesAndOrder(countries);
System.out.println(countries);
}
public static void removeDuplicatesAndOrder(List
{
Set
treeset.addAll(list);
list.clear();
list.addAll(treeset);
}
}
The output of the following program is as follows. It will be in sorted order as well as it does not contain any duplicates.
[Canada, Australia, Brazil, Canada, Egypt, Denmark]
[Australia, Brazil, Canada, Denmark, Egypt]
[Australia, Brazil, Canada, Denmark, Egypt]
Thank you for reading the post. Please comment below if you have any doubts. Any alternative solutions to remove duplicates and order a list is mostly welcome.
Related Topics:
1) Map and Sets in Java
2) Program to find the longest sequence in an array.
Comments
Post a Comment