Site icon Narayana Tutorial

Sorting List by using Comparator Interface

Sorting List by using Comparator Interface

In this article, I am going to explain the Sorting List by using Comparator Interface. Objects Type List can be sorted by using a Comparator interface. By using comparator we can sort the list of objects by a single field or multiple fields either in ascending order or descending order.

 

Here we have student data like first name, last name, and city. We can sort the student data by student first name either in ascending order or descending order.

Sort By Single Field

  1. StudentVo.java
  2. StudentDataCreate.java
  3. StudentFirstNameSorter.java
  4. ComparatorSorterBySingleField.java

Sort By Multiple Fields

  1. StudentVo.java
  2. StudentDataCreate.java
  3. StudentFirstNameSorter.java
  4. StudentLastNameSorter.java
  5. ComparatorSorterByMultipleFields.java

Sort By Single Field

StudentVo.java

package com.narayanatutorial.Comparator.SortBySingleFiled;

public class StudentVo {

	String studentFirstName;
	String studentLastName;
	String studentCity;
	
	
	public String getStudentFirstName() {
		return studentFirstName;
	}
	public void setStudentFirstName(String studentFirstName) {
		this.studentFirstName = studentFirstName;
	}
	public String getStudentLastName() {
		return studentLastName;
	}
	public void setStudentLastName(String studentLastName) {
		this.studentLastName = studentLastName;
	}
	public String getStudentCity() {
		return studentCity;
	}
	public void setStudentCity(String studentCity) {
		this.studentCity = studentCity;
	}
	
}

 

StudentDataCreate.java

package com.narayanatutorial.Comparator.SortBySingleFiled;

import java.util.ArrayList;
import java.util.List;

public class StudentDataCreate {
	private List<StudentVo> list;

	public List<StudentVo> getStudentData() {
		list = new ArrayList<StudentVo>();
		StudentVo st = null;
		st = new StudentVo();
		st.setStudentCity("Bangalore");
		st.setStudentFirstName("Narayana1");
		st.setStudentLastName("Ragi1");
		list.add(st);

		st = new StudentVo();
		st.setStudentCity("Bangalore");
		st.setStudentFirstName("Chandra");
		st.setStudentLastName("Sekhar");
		list.add(st);

		st = new StudentVo();
		st.setStudentCity("Chennai");
		st.setStudentFirstName("Ravi");
		st.setStudentLastName("Kumar2");
		list.add(st);

		st = new StudentVo();
		st.setStudentCity("Mumbai");
		st.setStudentFirstName("Ravi");
		st.setStudentLastName("Kumar1");
		list.add(st);

		return list;
	}
}

 

StudentFirstNameSorter.java

package com.narayanatutorial.Comparator.SortBySingleFiled;

import java.util.Comparator;

public class StudentFirstNameSorter implements Comparator<StudentVo> {

	public int compare(StudentVo o1, StudentVo o2) {

		return o1.getStudentFirstName().compareTo(o2.studentFirstName);
	}

}

 

ComparatorSorterBySingleField.java

package com.narayanatutorial.Comparator.SortBySingleFiled;

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

public class ComparatorSorterBySingleField {
	public static void main(String args[]) {
		StudentDataCreate sdc = new StudentDataCreate();

		List<StudentVo> list = sdc.getStudentData();
		System.out.println("Before First Name Sort \n***********************************");
		System.out.println("FirstName # LastName # City\n***********************************");
		list.forEach(x -> System.out
				.println(x.getStudentFirstName() + " # " + x.getStudentLastName() + " # " + x.getStudentCity()));

		// by using Comparator implemented class object
		// Collections.sort(list, new StudentFirstNameSorter());

		Collections.sort(list, new Comparator<StudentVo>() {
			@Override
			public int compare(StudentVo o1, StudentVo o2) {
				//By Ascending Order
				return o1.getStudentFirstName().compareTo(o2.getStudentFirstName());
				
				//By Descending Order
				//return o2.getStudentFirstName().compareTo(o1.getStudentFirstName());
			}
		});

		System.out.println("\nAfter First Name Sort \n***********************************");

		System.out.println("FirstName # LastName # City\n***********************************");

		list.forEach(x -> System.out
				.println(x.getStudentFirstName() + " # " + x.getStudentLastName() + " # " + x.getStudentCity()));

	}
}

Output

Before First Name Sort 
***********************************
FirstName # LastName # City
***********************************
Narayana1 # Ragi1 # Bangalore
Chandra # Sekhar # Bangalore
Ravi # Kumar2 # Chennai
Ravi # Kumar1 # Mumbai

After First Name Sort 
***********************************
FirstName # LastName # City
***********************************
Chandra # Sekhar # Bangalore
Narayana1 # Ragi1 # Bangalore
Ravi # Kumar2 # Chennai
Ravi # Kumar1 # Mumbai

 

Sort By Multiple Fields

 


 

ComparatorSorterByMultipleFields.java

 

package com.narayanatutorial.Comparator.SortByTwoFileds;

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

public class ComparatorSorterByMultipleFields {
	public static void main(String args[]) {
		StudentDataCreate sdc=new StudentDataCreate();
		
		List<StudentVo> list=sdc.getStudentData();
		
		System.out.println("Before First Name and Last Name Sort \n***********************************");
		System.out.println("FirstName # LastName # City\n***********************************");
		list.forEach(x -> System.out.println(x.getStudentFirstName()+" # "+x.getStudentLastName()+" # "+x.getStudentCity()));
		

		Collections.sort(list, new Comparator<StudentVo>() {
			@Override
			public int compare(StudentVo o1, StudentVo o2) {
				//By Ascending Order 
				int i=o1.getStudentFirstName().compareTo(o2.getStudentFirstName());
				
				//By Descending Order 
				//int i=o2.getStudentFirstName().compareTo(o1.getStudentFirstName());
				
				System.out.println("i:"+i);
				if(i != 0) {
					return i;
				}
				//By Ascending Order
				return o1.getStudentLastName().compareTo(o2.getStudentLastName());
				
				//By Descending Order
				//return o2.getStudentLastName().compareTo(o1.getStudentLastName());
			}
			
		});
		
		
	    System.out.println("\nAfter First Name and Last Name Sort \n***********************************");
	    
		System.out.println("FirstName # LastName # City\n***********************************");
		
	    list.forEach(x -> System.out.println(x.getStudentFirstName()+" # "+x.getStudentLastName()+" # "+x.getStudentCity()));
		
		
	}
}

Output

Before First Name and Last Name Sort 
***********************************
FirstName # LastName # City
***********************************
Narayana1 # Ragi1 # Bangalore
Chandra # Sekhar # Bangalore
Ravi # Kumar2 # Chennai
Ravi # Kumar1 # Mumbai
i:-11
i:15
i:4
i:4
i:0

After First Name and Last Name Sort 
***********************************
FirstName # LastName # City
***********************************
Chandra # Sekhar # Bangalore
Narayana1 # Ragi1 # Bangalore
Ravi # Kumar1 # Mumbai
Ravi # Kumar2 # Chennai

 

StudentLastNameSorter.java

package com.narayanatutorial.Comparator.SortByTwoFileds;

import java.util.Comparator;

public class StudentLastNameSorter implements Comparator<StudentVo> {

	public int compare(StudentVo o1, StudentVo o2) {
		
		return o1.getStudentLastName().compareTo(o2.getStudentLastName());
	}

}

ComparatorSorterByMultipleFieldsByJava18Feature.java

 

Collections.sort(list, new StudentFirstNameSorter().thenComparing(new StudentLastNameSorter()));

 

package com.narayanatutorial.Comparator.SortByTwoFileds;

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

public class ComparatorSorterByMultipleFieldsByJava18Feature {

	public static void main(String args[]) {
		StudentDataCreate sdc = new StudentDataCreate();

		List<StudentVo> list = sdc.getStudentData();

		System.out.println("Before First Name and Last Name Sort \n***********************************");
		System.out.println("FirstName # LastName # City\n***********************************");
		list.forEach(x -> System.out
				.println(x.getStudentFirstName() + " # " + x.getStudentLastName() + " # " + x.getStudentCity()));

		Collections.sort(list, new StudentFirstNameSorter().thenComparing(new StudentLastNameSorter()));

		System.out.println("\nAfter First Name and Last Name Sort \n***********************************");

		System.out.println("FirstName # LastName # City\n***********************************");

		list.forEach(x -> System.out
				.println(x.getStudentFirstName() + " # " + x.getStudentLastName() + " # " + x.getStudentCity()));

	}
}

 

Get full source code from Git.