Sorting In Java

Today I am writing this article to show case by how many ways sorting can be implemented in Java.

Here are some examples of sorting by Java 8.

By Stream API:

By Converting List into stream just by listName.stream() and then apply sorted method for sorting the List.

For Ascending Order
List<Integer> lstInt=Arrays.asList(8,1,2,3,5);
lstInt.stream().sorted().forEach(System.out::print);

Output: [1,2,3,5,8]

For Descending Order
lstInt.stream().sorted(Comparator.reverseOrder()).forEach(System.out::print);

Output: [8,5,3,2,1]        

For Ascending order keep we can just do by listName.sort() i.e the default behavior.

For Descending order just need to pass the order i.e Comparator.reverseOrder() in the sorted method as an argument.

listName.sorted(Comparator.reverseOrder())

Article content
Internal implementation snippet

The sorted method accepts Comparator Implementation and by using Comparator.reverseOrder() returns Collections.reverseOrder();

Article content

By sort method of List Interface

Another way of sorting is by using the sort method of List Interface.

Lets straight away look into the example.

Ascending Order

List<Integer> lstInt=Arrays.asList(8,1,2,3,5);
lstInt.sort(Comparator.naturalOrder());    
//Natural order defines ascending order

Descending order

lstInt.sort(Comparator.reverseOrder());  

OR 

lstInt.sort((num1,num2)->num1.compareTo(num2));   
// Implementation of Comparator Interface by lambda

Descending order

lstInt.sort((num1,num2)->num2.compareTo(num1));  // Just Reverse num1 and num2         

Lets take one example of List of String for sorting.

List<String> country = Arrays.asList("Russia", "India", "China", "Japan", "", "Ghana"); 

country.sort(String.CASE_INSENSITIVE_ORDER); 
 //sorts the list in case insensitive order 

country.sort(Comparator.naturalOrder());    //sorts list in ascending order 
//sorts list in ascending order (null, capital letter and small letter) if any        

By Collections Class

Let's Straight jump into example,

Here we need to just pass the List as argument of sort method and the List will be sorted.

Ascending order

Collections.sort(lstString);

Descending order

Collections.sort(lstString,Comparator.reverseOrder());        

Sorting on List of Beans / POJO / DTO

Say you have a bean Named Consultant and properties are name , age and salary.

public class Consultant {
String name;
long Salary;
int age;
	
public Consultant(String name, long salary,int age) {
		super();
		this.name = name;
		this.Salary= salary;
		this.age=age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getSalary() {
		return Salary;
	}
	public void setSalary(long salary) {
		Salary = salary;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getAge() {
		return age;
	}
	@Override
	public String toString() {
		return "Consultant [name=" + name + ", Salary=" + Salary + ", age=" + age + "]";
	}
}        

Sort based on Salary

List<Consultant> lstConsultant = Arrays.asList(new Consultant("Tim", 3500, 28),new Consultant("Jack", 4000, 30)); 

Ascending order

lstConsultant.sort(Comparator.comparing(Consultant::getSalary);

Descending order

lstConsultant.sort(Comparator.comparing(Consultant::getSalary,Comparator.reverseOrder());        

Sort based on age

Ascending order

lstConsultant.sort(Comparator.comparing(Consultant::getAge);

Descending order

lstConsultant.sort(Comparator.comparing(Consultant::getAge,,Comparator.reverseOrder());        

Lets Say if Some one asks I want data with the max salary and lowest age then?

We have solution for that we can chain up the comparisons by using keyword thenComparing(new Comparator Implementation) lets see by example below.

lstConsultant.sort(Comparator.comparing(Consultant::getAge).thenComparing(Consultant::getSalary,Comparator.reverseOrder()));

//Here age will be in ascending order and salary will be in descending order        

Please try to implement the same in your day to day coding to get more used to it.

Let me know if any Questions or queries in comments.

To view or add a comment, sign in

More articles by Kushal Baldev

  • Spring Boot 3 + Security Understanding

    As we all know about the Spring Security implementation that we have done once at the start of any new application…

    2 Comments
  • Map and Reduce in Streams Java

    Let us consider the two mostly used operators in Java Stream API. MAP MAP operator is an intermediate operator for…

    1 Comment

Explore content categories