$show=/label

Collections sort() in Java - List Custom Sort Example

SHARE:

A complete guide to Sorting Custom Objects in java. Collections.sort() method does the sorting based on Comparable or Comparator implementation. Example custom sorting for sorting Employee objects

1. Introduction


In this tutorial, You'll learn how to sort Custom objects in java. First, We'll show the example program to sort List of Strings and Next move to the Custom sorting of Arraylist of Employee's. Sorting is done by Empoyee Id, Name and age. All examples shown are on GitHub at the end of this article.

2. Collections.sort() Example


Collections class has a method sort() which takes List implementation such as ArrayList, LinkedList etc.

Now, Creating a list with String values and sort the values using Collections.sort() method.

Collections.sort() method does the sorting in ascending order by default. All the values are added to the list must implement Comparable interface.

If null is passed to sort() method it throws java.lang.NullPointerException.


2.1 Soring List of Strings


package com.java.w3schools.blog.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * Collections.sort() example to sort List of Strngs.
 * 
 * @author JavaProgramTo.com
 *
 */
public class CollectionSortExample {

 public static void main(String[] args) {

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

  countries.add("Singapore");
  countries.add("India");
  countries.add("USA");
  countries.add("UK");
  countries.add("Australia");

  System.out.println("List of countires before sorting : ");

  Iterator<String> it = countries.iterator();

  while (it.hasNext()) {
   System.out.println(it.next());
  }
  Collections.sort(countries);

  System.out.println("List of countries after sorting :");

  it = countries.iterator();

  while (it.hasNext()) {
   System.out.println(it.next());
  }

 }

}

Output:

List of countires before sorting : 
Singapore
India
USA
UK
Australia

List of countries after sorting :
Australia
India
Singapore
UK
USA

2.2 Sorting List of Integers


List of integer prime numbers sorting program.

package com.java.w3schools.blog.collections.sorting;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * Collections.sort() example to sort List of Strngs.
 * 
 * @author JavaProgramTo.com
 *
 */
public class CollectionSortIntegersExample {

 public static void main(String[] args) {

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

  primeNumbers.add(19);
  primeNumbers.add(7);
  primeNumbers.add(37);
  primeNumbers.add(59);
  primeNumbers.add(23);

  System.out.println("List of integer prime numnbers before sorting : ");

  Iterator<Integer> it = primeNumbers.iterator();

  while (it.hasNext()) {
   System.out.println(it.next());
  }
  Collections.sort(primeNumbers);

  System.out.println("List of integer prime numnbers after sorting :");

  it = primeNumbers.iterator();

  while (it.hasNext()) {
   System.out.println(it.next());
  }

 }

}

Output:

List of integer prime numnbers before sorting : 
19
7
37
59
23

List of integer prime numnbers after sorting :
7
19
23
37
59

See the above two program are sorted in ascending order from low to high values for integers and string in alphabetical order.

If different type of objects are passed then will get ClassCastException as below.

public class CollectionSortClassCastException {

 public static void main(String[] args) {

  List values = new ArrayList();

  values.add("Singapore");
  values.add(737);
  values.add(2323f);

  Collections.sort(values);

 }

}

Error:

Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
 at java.base/java.lang.Integer.compareTo(Integer.java:64)
 at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
 at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
 at java.base/java.util.Arrays.sort(Arrays.java:1316)
 at java.base/java.util.Arrays.sort(Arrays.java:1510)
 at java.base/java.util.ArrayList.sort(ArrayList.java:1749)
 at java.base/java.util.Collections.sort(Collections.java:143)
 at com.java.w3schools.blog.collections.sorting.CollectionSortClassCastException.main(CollectionSortClassCastException.java:25)

2.3 Sorting in Descending Order


Passing Comparator to the sort() method will do sorting in reverse order to ascending order. reverseOrder() method returns a comparator to reverse the natural ordering.

Collections.sort(countries, Collections.reverseOrder())
Collections.sort(primeNumbers, Collections.reverseOrder())

3. Java Custom Sorting With Employee Objects


As of now, shown the example programs with Strings and Integers. There is a common scenario for sorting user-defined objects, every interviewer look for the better collection concepts understanding.

We will demonstrate the example with Employe class sorting by id.

First, Create Employee class with id, name and age.

Next, Implement Comparable interface and provide implementation to compareTo() method.

package com.java.w3schools.blog.collections.sorting;

public class Employee implements Comparable<Employee> {

 private int id;
 private String name;
 private int age;

 public Employee(int id, String name, int age) {
  super();
  this.id = id;
  this.name = name;
  this.age = age;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 @Override
 public int compareTo(Employee o) {

  if (o.getId() > this.getId()) {
   return 1;
  } else if (o.getId() < this.getId()) {
   return -1;
  }

  return 0;

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

}

3.1 Sorting List of Employee objects by ID



package com.java.w3schools.blog.collections.sorting;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class CustomEmplpoyeeSortById {

 public static void main(String[] args) {

  List<Employee> emps = new ArrayList<>();

  emps.add(new Employee(2001, "Modi", 55));
  emps.add(new Employee(1901, "Trumph", 57));
  emps.add(new Employee(1950, "Boris Johnson", 56));

  System.out.println("Before sorting custom list of employees : ");
  Iterator<Employee> it = emps.iterator();
  while (it.hasNext()) {
   System.out.println(it.next());
  }
  Collections.sort(emps);

  System.out.println("After sorting custom list of employees in natural order: ");
  it = emps.iterator();
  while (it.hasNext()) {
   System.out.println(it.next());
  }

  Collections.sort(emps, Collections.reverseOrder());

  System.out.println("After sorting custom list of employees in decendng order: ");
  it = emps.iterator();
  while (it.hasNext()) {
   System.out.println(it.next());
  }

 }

}

Output:

Before sorting custom list of employees : 
Employee [id=2001, name=Modi, age=55]
Employee [id=1901, name=Trumph, age=57]
Employee [id=1950, name=Boris Johnson, age=56]

After sorting custom list of employees in natural order: 
Employee [id=2001, name=Modi, age=55]
Employee [id=1950, name=Boris Johnson, age=56]
Employee [id=1901, name=Trumph, age=57]

After sorting custom list of employees in decendng order: 
Employee [id=1901, name=Trumph, age=57]
Employee [id=1950, name=Boris Johnson, age=56]
Employee [id=2001, name=Modi, age=55]


3.2 Sorting List of Employee objects by Name


Change the comparision bu name.

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


now run the program that generates the sorting by name.

Before sorting custom list of employees : 
Employee [id=2001, name=Modi, age=55]
Employee [id=1901, name=Trumph, age=57]
Employee [id=1950, name=Boris Johnson, age=56]

After sorting custom list of employees by name in natural order: 
Employee [id=1950, name=Boris Johnson, age=56]
Employee [id=2001, name=Modi, age=55]
Employee [id=1901, name=Trumph, age=57]

After sorting custom list of employees by name in decendng order: 
Employee [id=1901, name=Trumph, age=57]
Employee [id=2001, name=Modi, age=55]
Employee [id=1950, name=Boris Johnson, age=56]

3.3 Sorting List of Employee objects by Age


Change the comparsion basedon the age in Employee class.

@Override
public int compareTo(Employee o) {

 if (o.getAge() > this.getAge()) {
  return 1;
 } else if (o.getAge() < this.getAge()) {
  return -1;
 }

 return 0;

}

Output:

Before sorting custom list of employees : 
Employee [id=2001, name=Modi, age=55]
Employee [id=1901, name=Trumph, age=57]
Employee [id=1950, name=Boris Johnson, age=56]

After sorting custom list of employees by age in natural order: 
Employee [id=1901, name=Trumph, age=57]
Employee [id=1950, name=Boris Johnson, age=56]
Employee [id=2001, name=Modi, age=55]

After sorting custom list of employees by age in decendng order: 
Employee [id=2001, name=Modi, age=55]
Employee [id=1950, name=Boris Johnson, age=56]
Employee [id=1901, name=Trumph, age=57]


4. Java 8 Custom Sorting - Comparator


By using lambda expressions in Java 8, we can write the custom comparator in single line as below.

Comparator<Employee> compareByName = (Employee o1, Employee o2) -> o1.getName().compareTo( o2.getName() );

Collections.sort(emps, compareByName);

The above code generates the same output as seen in the section 3 examples.

5. Conclusion


In this article, We've seen how to sort the list of Strings and Integers in java. Sorting List in ascending and decending order. Possible errors with example programs.

And also, Custom sort based on Employee Id, Name and age variables.

GitHub Code

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Collections sort() in Java - List Custom Sort Example
Collections sort() in Java - List Custom Sort Example
A complete guide to Sorting Custom Objects in java. Collections.sort() method does the sorting based on Comparable or Comparator implementation. Example custom sorting for sorting Employee objects
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/java-collection-sort-custom-sorting.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/java-collection-sort-custom-sorting.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content