Java Collections Sort Strings, Wrapper Classes and Objects in Ascending or Descending Order

Overview

In this post, we will learn Collections sorting examples such as sorting Strings, Wrapper Classes and User-Defined objects in ascending and descending order.
String class and Wrapper classes implement the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.
Collections Utility class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSetCollections class provides methods for sorting the elements of List type elements.

Sorting in Collections Examples

  1. Sort Strings in Ascending Order
  2. Sort Strings in Descending Order
  3. Wrapper Classes in Ascending Order
  4. Wrapper Classes in Descending Order
  5. Sort User-Defined Objects in Ascending Order(Comparable Interface)
  6. Sort User-Defined Objects in Descending Order(Comparable Interface)
  7. Sort User-Defined Objects using Comparator Interface

1. Sort Strings in Ascending Order

In this example, we will sort the String objects in Ascending Order using Collections.sort() method.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortStringsExample {
    public static void main(String[] args) {
        sortStringsInAscOrder();
    }

    private static void sortStringsInAscOrder() {
        List<String> names = new ArrayList<>();
        names.add("ABC");
        names.add("ACB");
        names.add("PQR");
        names.add("CDQ");

        System.out.println("Before Sorting : " + names);
        Collections.sort(names);
        System.out.println("After Sorting in Asc Order: " + names);
    }
}

2. Sort Strings in Descending Order

In this example, we will sort the String objects in Descending Order using Collections.sort(names,Collections.reverseOrder()) method.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortStringsExample {
    public static void main(String[] args) {
         sortStringsInDescOrder();
    }

    private static void sortStringsInDescOrder() {
        List<String> names = new ArrayList<>();
        names.add("ABC");
        names.add("ACB");
        names.add("PQR");
        names.add("CDQ");

        System.out.println("Before Sorting : " + names);
        Collections.sort(names,Collections.reverseOrder());
        System.out.println("After Sorting in Desc Order : " + names);
    }
}

 3. Wrapper Classes in Ascending Order

In this example, we will take Integer wrapper class and sort it in ascending order by using Collections.sort() method.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortWrappersExample {
 
    public static void main(String[] args) {
        sortWrapperClassObjectsInAsc();
    }
    private static void sortWrapperClassObjectsInAsc() {
        List<Integer> names = new ArrayList<>();
        names.add(100);
        names.add(20);
        names.add(10);
        names.add(50);

        System.out.println("Before Sorting : " + names);
        Collections.sort(names);
        System.out.println("After Sorting : " + names);
    }
}
Output:
Before Sorting : [100, 20, 10, 50]
After Sorting : [10, 20, 50, 100]

4. Wrapper Classes in Descending Order

In this example, we will take Integer wrapper class and sort it in descending order by using Collections.sort(names,Collections.reverseOrder()) method.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortWrappersExample {
 
 public static void main(String[] args) {
  sortWrapperClassObjectsInDesc();
 }
 private static void sortWrapperClassObjectsInDesc() {
  List<Integer> names = new ArrayList<>();
  names.add(100);
  names.add(20);
  names.add(10);
  names.add(50);

  System.out.println("Before Sorting : " + names);
  Collections.sort(names,Collections.reverseOrder());
  System.out.println("After Sorting : " + names);
 }
}
Output:
Before Sorting : [100, 20, 10, 50]
After Sorting : [100, 50, 20, 10]

5. Sort User-Defined Objects in Ascending Order

This is example demonstrate that we create a list of person objects and we compare each person's age by using compateTo() method of Comparable Interface. In short, we are sorting persons by age in ascending order.
public class Person implements Comparable<Person> {

 private int id;

 private String name;

 private int age;

 public Person(int id, String name, int age) {
  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 String toString() {
  return this.name;
 }

 @Override
 public int compareTo(Person otherPerson) {
  return (this.getAge() - otherPerson.getAge());
 }
}
import java.util.ArrayList;

import java.util.Collections;
import java.util.List;

public class PersonSorterInASC {
 public static void main(String[] args) {

  sortUserDefinedObjectsInAsc();
 }

 private static void sortUserDefinedObjectsInAsc() {
  List<Person> persons = new ArrayList<Person>();
  Person person1 = new Person(59, "John", 40);
  Person person12 = new Person(67, "Roger", 25);
  Person person13 = new Person(45, "Steven", 30);
  persons.add(person1);
  persons.add(person12);
  persons.add(person13);

  System.out.println("Before Sorting : " + persons);
  Collections.sort(persons);
  System.out.println("After Sorting : " + persons);
 }
}
Output:
Before Sorting : [John, Roger, Steven]
After Sorting : [Roger, Steven, John]

6. Sort User-Defined Objects in Descending Order

Java provides in build utility method sort() and Comparator Collections.reverseOrder() to sort the objects in descending order.

Collections.reverseOrder()

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
Collections.sort(persons, Collections.reverseOrder());
This example demonstrates that we are sorting person objects by age in descending order.
public class PersonSorterInDESC {

 public static void main(String[] args) {
  sortUserDefinedObjectsinDesc();
 }
 
 private static void sortUserDefinedObjectsinDesc(){
  List<Person> persons = new ArrayList<Person>();
  Person person1 = new Person(59, "John", 40);
  Person person12 = new Person(67, "Roger", 25);
  Person person13 = new Person(45, "Steven", 30);
  persons.add(person1);
  persons.add(person12);
  persons.add(person13);

  System.out.println("Before Sorting : " + persons);
  Collections.sort(persons, Collections.reverseOrder());
  
  System.out.println(" Sort in decending order : " + persons);

 }
}
Output:
Before Sorting : [John, Roger, Steven]
Sort in decending order : [John, Steven, Roger]

7. Sort User-Defined Objects using Comparator Interface

```java
import java.time.LocalDate;

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

public class ComparatorExample {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();

        employees.add(new Employee(1010, "Rajeev", 100000.00, LocalDate.of(2010, 7, 10)));
        employees.add(new Employee(1004, "Chris", 95000.50, LocalDate.of(2017, 3, 19)));
        employees.add(new Employee(1015, "David", 134000.00, LocalDate.of(2017, 9, 28)));
        employees.add(new Employee(1009, "Steve", 100000.00, LocalDate.of(2016, 5, 18)));

        System.out.println("Employees : " + employees);

        // Sort employees by Name
        Collections.sort(employees, Comparator.comparing(Employee::getName));
        System.out.println("\nEmployees (Sorted by Name) : " + employees);

        // Sort employees by Salary
        Collections.sort(employees, Comparator.comparingDouble(Employee::getSalary));
        System.out.println("\nEmployees (Sorted by Salary) : " + employees);

        // Sort employees by JoiningDate
        Collections.sort(employees, Comparator.comparing(Employee::getJoiningDate));
        System.out.println("\nEmployees (Sorted by JoiningDate) : " + employees);

        // Sort employees by Name in descending order
        Collections.sort(employees, Comparator.comparing(Employee::getName).reversed());
        System.out.println("\nEmployees (Sorted by Name in descending order) : " + employees);

        // Chaining multiple Comparators
        // Sort by Salary. If Salary is same then sort by Name
        Collections.sort(employees, Comparator.comparingDouble(Employee::getSalary)
                   .thenComparing(Employee::getName));
        System.out.println("\nEmployees (Sorted by Salary and Name) : " + employees);
    }
}
Output:
Employees : [Employee{id=1010, name='Rajeev', salary=100000.0, joiningDate=2010-07-10}, 
Employee{id=1004, name='Chris', salary=95000.5, joiningDate=2017-03-19}, 
Employee{id=1015, name='David', salary=134000.0, joiningDate=2017-09-28},
 Employee{id=1009, name='Steve', salary=100000.0, joiningDate=2016-05-18}]

Employees (Sorted by Name) : 
[Employee{id=1004, name='Chris', salary=95000.5, joiningDate=2017-03-19}, 
Employee{id=1015, name='David', salary=134000.0, joiningDate=2017-09-28},
 Employee{id=1010, name='Rajeev', salary=100000.0, joiningDate=2010-07-10}, 
Employee{id=1009, name='Steve', salary=100000.0, joiningDate=2016-05-18}]

Employees (Sorted by Salary) : 
[Employee{id=1004, name='Chris', salary=95000.5, joiningDate=2017-03-19},
 Employee{id=1010, name='Rajeev', salary=100000.0, joiningDate=2010-07-10},
 Employee{id=1009, name='Steve', salary=100000.0, joiningDate=2016-05-18}, 
Employee{id=1015, name='David', salary=134000.0, joiningDate=2017-09-28}]

Employees (Sorted by JoiningDate) : 
[Employee{id=1010, name='Rajeev', salary=100000.0, joiningDate=2010-07-10},
 Employee{id=1009, name='Steve', salary=100000.0, joiningDate=2016-05-18},
 Employee{id=1004, name='Chris', salary=95000.5, joiningDate=2017-03-19}, 
Employee{id=1015, name='David', salary=134000.0, joiningDate=2017-09-28}]

Employees (Sorted by Name in descending order) : 
[Employee{id=1009, name='Steve', salary=100000.0, joiningDate=2016-05-18}, 
Employee{id=1010, name='Rajeev', salary=100000.0, joiningDate=2010-07-10},
 Employee{id=1015, name='David', salary=134000.0, joiningDate=2017-09-28}, 
Employee{id=1004, name='Chris', salary=95000.5, joiningDate=2017-03-19}]

Employees (Sorted by Salary and Name) :
 [Employee{id=1004, name='Chris', salary=95000.5, joiningDate=2017-03-19},
 Employee{id=1010, name='Rajeev', salary=100000.0, joiningDate=2010-07-10},
 Employee{id=1009, name='Steve', salary=100000.0, joiningDate=2016-05-18}, 
Employee{id=1015, name='David', salary=134000.0, joiningDate=2017-09-28}]

Convert Collections Examples


Comments