HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

Java sort ArrayList of custom objects by field – Collections.sort() example

By Lokesh Gupta | Filed Under: Sort

Learn to use Collections.sort() method to sort arraylist of custom objects in java with examples. By default, this method sorts the unsorted list into ascending order, according to the natural ordering of its elements. We can use Collections.reverseOrder() method for reverse sorting.

1. Sort ArrayList of objects – Collections.sort( list )

  1. It sorts the specified list into ascending order or their natural order.
  2. All elements in the list must implement the Comparable interface.
  3. All elements in the list must be mutually comparable and should not throw ClassCastException.
  4. This sort is guaranteed to be stable. It means that equal elements will not be reordered as a result of the sort.
  5. The specified list must be modifiable, but need not be resizable.
  6. Method does not return any value.

1.1. Sort arraylist of strings

List<String> names = Arrays.asList("Alex", "Charles", "Brian", "David");

//Natural order
Collections.sort(names);	//[Alex, Brian, Charles, David]

//Reverse order
Collections.sort(names, Collections.reverseOrder());	[David, Charles, Brian, Alex]	

1.2. Sort arraylist of custom objects by field with Comparable

We may need to sort list of user defined objects which have their own sorting logic. In that case, implement the Comparator interface in those domain class and use same approach as above.

The domain object Employee is as below. Checkout for comparison logic in compareTo() method.

public class Employee implements Comparable< Employee >{
 
    private Integer id;
    
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + "]";
	}

	@Override
	public int compareTo(Employee o) {
		return this.getId().compareTo(o.getId());
	}
}

Java program to sort list of employee objects by id, in ascending and descending orders.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class JavaSort 
{
	public static void main(String[] args) 
	{
		ArrayList<Employee> employees = getUnsortedEmployeeList();
		
		//1. Employee ids in ascending order
		Collections.sort(employees);
		
		System.out.println(employees);
		
		//2. Employee ids in reverse order
		Collections.sort(employees, Collections.reverseOrder());
		
		System.out.println(employees);
	}

	//Returns an unordered list of employees
	private static ArrayList<Employee> getUnsortedEmployeeList() 
	{
		ArrayList<Employee> list = new ArrayList<>();
		Random rand = new Random(10);
        
        for(int i = 0; i < 5; i++) 
        {
            Employee e = new Employee();
            e.setId(rand.nextInt(100));
            list.add(e);
        }
        return list;
	}
}

Program output.

[E [id=13], E [id=46], E [id=80], E [id=90], E [id=93]]
[E [id=93], E [id=90], E [id=80], E [id=46], E [id=13]]

2. Sort ArryList of objects – Collections.sort( list, Comparator )

If domain object does not implement Comparable interface, then we can use custom Comparator implementations. Use lambda expression to even more shorten the syntax.

2.1. Create Custom Comparators

This is general syntax to create a comparator in Java.

Comparator<Employee> compareById = new Comparator<Employee>() {
	@Override
	public int compare(Employee o1, Employee o2) {
		return o1.getId().compareTo(o2.getId());
	}
};

If in Java 8, use lambda expression to make the syntax more readable.

Comparator<Employee> compareById = (Employee o1, Employee o2) -> 
									o1.getId().compareTo( o2.getId() );

//use any other field

//First name sorter
Comparator<Employee> compareByFirstName = (Employee o1, Employee o2) ->
									o1.getFirstName().compareTo( o2.getFirstName() );
//Last name sorter
Comparator<Employee> compareByLastName = (Employee o1, Employee o2) -> 
									o1.getLastName().compareTo( o2.getLastName() );

2.2. Sort list of objects by field with Comparator

ArrayList<Employee> employees = getUnsortedEmployeeList();
			
Comparator<Employee> compareById = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() );

Collections.sort(employees, compareById);

Collections.sort(employees, compareById.reversed());

Program output.

[E [id=13], E [id=46], E [id=80], E [id=90], E [id=93]]
[E [id=93], E [id=90], E [id=80], E [id=46], E [id=13]]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

References:

Collections.sort()
List.sort()

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Help me fight spammers. Solve this simple math. *

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Java Sorting

  • Java – Sorting
  • Java – Sort String
  • Java – Sort Array
  • Java – Sort ArrayList
  • Java – Object Sorting
  • Java – Collections.sort()
  • Java – Comparator.theComparing()
  • Java – Sort Map by values
  • Java – Sort Map by key
  • Java – Sort on multiple fields

Java Collections

  • Collections Framework
  • Array
  • ArrayList
  • LinkedList
  • HashMap
  • Hashtable
  • LinkedHashMap
  • TreeMap
  • HashSet
  • LinkedHashSet
  • TreeSet
  • Comparable
  • Comparator
  • Iterator
  • ListIterator
  • Spliterator
  • PriorityQueue
  • PriorityBlockingQueue
  • ArrayBlockingQueue
  • LinkedTransferQueue
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet
  • Collection Sorting
  • Interview Questions

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap