Sort ArrayList attribute from objects by object

I have an Arraylist of Objects. This object has an attribute or data type - "String". I need to sort Arraylist by this line. How to achieve this?

+7
java string sorting arraylist
source share
2 answers

You need to write Comparator<MyObject> and use Collections.sort(List<T>, Comparator<? super T> to sort the List .

Or, your MyObject can also implements Comparable<MyObject> , defining a natural order that compares with your specific attribute, and then use Collections.sort(List<T> instead.

see also

Related Questions

When sorting a List by various criteria:

  • Sort ArrayList from Contacts

On Comparator and Comparable

  • When to use Comparable vs Comparator
  • difference between compare () and compareTo ()
  • Comparable and comparative contract regarding zero
  • Why does the Java collection structure offer two sorting methods?
+13
source share

Another good way to do this, which is a bit more flexible if there is more than one property of an object that you might want to sort, is to use Guava Ordering with its onResultOf(Function) option. This is ideal for sorting by property, since Function can be used to retrieve and return a specific property of an object. For a simple example, imagine a Person class with the String getFirstName() and String getLastName() methods.

 List<Person> people = ...; Collections.sort(people, Ordering.natural().onResultOf( new Function<Person, String>() { public String apply(Person from) { return from.getFirstName(); } })); 

The above will sort the list by name.

To make it more enjoyable, you can define functions that you might want to use as public static final fields in the Person class. Then you can sort by last name as follows:

 Collections.sort(people, Ordering.natural().onResultOf(Person.GET_LAST_NAME)); 

As a wonderful note, all this will be much easier in Java 8 with lambda expressions and method references. You can write something like this without having to define clumsy anonymous inner classes or static end fields:

 import static java.util.Comparator.comparing; ... people.sort(comparing(Person::getLastName)); 
+6
source share

All Articles