简体   繁体   中英

how to sort a list of objects for duplicates

How to sort a list of objects for duplicates in java?basically that every object should be uniqe in list after sorting. Maybe someone knows a good example.

You can add the elements of the List to a Set, and then create a new List with those elements, like this:

List<Object> originalList = new ArrayList<Object>();
// the elements of originalList get added here

Set<Object> set = new HashSet<Object>(originalList);
List<Object> newList = new ArrayList<Object>(set);

Be aware that:

  • I'm using Object as the type for the List and Set, replace it with the appropriate type to suit your needs
  • For the above to work correctly, the objects in the list must override both hashCode and equals
  • The elements in the new list will be in different order from those in the original list

To obtain a collection of only the unique elements from a list, you can just add all the elements to a Set .

List<String> l = new ArrayList<String>();
Set<String> s = new HashSet<String>(l);

If you just want to remove duplicates, try this:

List<Object> l; //Your list of data

for(int i = l.size()-1; i > 0; i--)
  for(int j = i; j > 0; j--)
    if(l.get(i).equals(l.get(j))) //or == for primitives
      l.remove(j);

If you have a specific sort you want to apply, you can do it within the same for loop after the if statement. That's really the only advantage of this over a HashSet .

As others have already pointed out, you can use a Set data structure. But since you are looking for a sorted list, instead of using HashSet, you can go for a TreeSet , whose elements are sorted in the natural order by default.

Eg:

List<Integer> list = new ArrayList<Integer>();

list.add(8);
list.add(5);
list.add(3);
list.add(5);
list.add(9);

Set<Integer> s = new TreeSet<Integer>(list);

Iterator<Integer> itr = s.iterator();
while(itr.hasNext()) {
    System.out.print(itr.next() + " ");
}

Output:

3 5 8 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM