Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a collection of objects [duplicate]

If I have a simple list of Strings:

List<String> stringList = new ArrayList<String>(); 

I can sort it with:

Collections.sort(stringList); 

But suppose I have a Person class:

public class Person {    private String name;    private Integer age;    private String country; } 

And a list of it:

List<Person> personList = new ArrayList<Person>(); 

And I want to sort it sometimes by name, sometimes by age, sometimes by country.

What is the easiest way to accomplish that?

I know that I can implement the Comparable interface, but that seems to limit me to sort it by one specific property.

like image 820
Knut Arne Vedaa Avatar asked Jul 30 '09 11:07

Knut Arne Vedaa


People also ask

Does sorting remove duplicates?

sort(comparator) removes duplicates. There is no extra parameter to preserve duplicates.

Can sorted Set have duplicates?

The SortedSet<T> class does not accept duplicate elements.

How do you sort a collection of objects?

Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

Can sorted list have duplicate keys?

A SortedList does not allow duplicate keys. Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. Elements in this collection can be accessed using an integer index.


1 Answers

Collections.sort can be called with a custom comparator. And that comparator can be implemented to allow sorting in different sort orders. Here's an example (for your Person model - with age as an Integer):

public class FlexiblePersonComparator implements Comparator<Person> {   public enum Order {Name, Age, Country}    private Order sortingBy = Name;    @Override   public int compare(Person person1, Person person2) {     switch(sortingBy) {       case Name: return person1.name.compareTo(person2.name);       case Age: return person1.age.compareTo(person2.age);       case Country: return person1.country.compareTo(person2.country);     }     throw new RuntimeException("Practically unreachable code, can't be thrown");   }    public void setSortingBy(Order sortBy) {     this.sortingBy = sortingBy;   } } 

And you use it like that (assuming persons is a field):

public void sortPersonsBy(FlexiblePersonComparator.Order sortingBy) {   List<Person> persons = this.persons;  // useless line, just for clarification   FlexiblePersonComparator comparator = new FlexiblePersonComparator();   comparator.setSortingBy(sortingBy);   Collections.sort(persons, comparator); // now we have a sorted list } 
like image 187
Andreas Dolk Avatar answered Sep 23 '22 22:09

Andreas Dolk