Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting ArrayList of Objects by Object attribute

I am having an Arraylist of Objects. Those object have an attribute or datatype - 'String'. I need to sort the Arraylist by that string. How to achieve this?

like image 718
Vishal Avatar asked Jul 27 '10 10:07

Vishal


People also ask

How can you sort an ArrayList of objects?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

How do you sort a list of objects based on an attribute of the objects in Java 8?

Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.

How do you sort an ArrayList by a parameter?

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.


1 Answers

Another good way of doing this that is a bit more flexible if there is more than one property of an object that you may wish to sort by is to use Guava's Ordering class with its onResultOf(Function) option. This is ideally suited for sorting by properties since a Function can be used to retrieve and return a specific property of an object. For a simple example, imagine a class Person with 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 first name.

To make it read nicer, you may want to define the functions you might want to use as public static final fields on the Person class. Then you could sort by last name like this:

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

As a fun aside note, this will all be a lot easier in Java 8 with lambda expressions and method references. You'll be able to write something like this without having to define any clumsy anonymous inner classes or static final fields:

import static java.util.Comparator.comparing;
...

people.sort(comparing(Person::getLastName));
like image 101
ColinD Avatar answered Sep 24 '22 08:09

ColinD