Pages

Saturday, April 11, 2020

Collections sort() in Java - List Custom Sort Example

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

No comments:

Post a Comment

Please do not add any spam links in the comments section.