Skip to main content

sort list of objects using comparator in java

 sort list of objects using comparator in java

one of the most important question for interviews of java programmer is how to sort list of objects in java , lets understand the solution using scenario of Patients , we will create a class Patient with two properties patientId and patientName and then we will provide options to sort list of patients by patientId and PatientName.

Step 1 :  create Patient.java class as below :

package com.sorting.sv;
public class Patient {
	private int patientId;
	private String patientName;
	public Patient() {
	}
	public Patient(int patientId, String patientName) {
		this.patientId = patientId;
		this.patientName = patientName;
	}
	public int getPatientId() {
		return patientId;
	}
	public void setPatientId(int patientId) {
		this.patientId = patientId;
	}
	public String getPatientName() {
		return patientName;
	}
	public void setPatientName(String patientName) {
		this.patientName = patientName;
	}
	@Override
	public String toString() {
		return "Patient [patientId=" + patientId + ", patientName=" + patientName + "]";
	}	
}

Step 2: Now In patient class we have two variables , patientId and patientName as we want to sort by both , lets create sorter classes by implementing Comparator interface. for sorting by patientId , create IdSorter.java class as below :

package com.sorting.sv;

import java.util.Comparator;

public class IdSorter implements Comparator<Patient> {

	@Override
	public int compare(Patient p1, Patient p2) {
	if(p1.getPatientId()>p1.getPatientId()) {
		return 1;
	}
	else if(p1.getPatientId()<p2.getPatientId()) {
		return -1;
	}else {
		return 0;
	}
	}

}


for sorting patients by name create NameSorter.java class as below :

package com.sorting.sv;
import java.util.Comparator;
public class NameSorter implements Comparator<Patient>{
 @Override
 public int compare(Patient o1, Patient o2) {	
	return o1.getPatientName().compareTo(o2.getPatientName());
 }
}

finally for testing write main class as below :

package com.sorting.sv;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class TestSorting {
	public static void main(String[] args) {
		List<Patient> myPatientList = Arrays.asList(new Patient(3, "A"), new Patient(1, "C"), new Patient(2, "B"));
		Scanner scn = new Scanner(System.in);
		int option = 0;
		try {
			System.out.println("original list is :");
			for(Patient patient:myPatientList) {
			System.out.println(patient);
			}
			do {
			System.out.println("Enter 1 for Sort by Id");
			System.out.println("Enter 2 for Sort by Name");
			System.out.println("Enter 0 for EXIT:");
			option = scn.nextInt();
			if (option == 1) {
				Collections.sort(myPatientList, new IdSorter());
				System.out.println("List sorted by patientId");
				for(Patient patient:myPatientList) {
					System.out.println(patient);
				}
			}
			else if (option == 2) {
				System.out.println("List sorted by patientName");
				Collections.sort(myPatientList, new NameSorter());
				for(Patient patient:myPatientList) {
					System.out.println(patient);
				}
			}
			else if(option == 0) {
				System.out.println("Exited successfuly");
			}
			else {
				System.out.println("Please enter 1 or 2 or 3 :");
			}
			}while(option!=0);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			scn.close();
		}
	}
}


Output :

original list is :
Patient [patientId=3, patientName=A]
Patient [patientId=1, patientName=C]
Patient [patientId=2, patientName=B]
Enter 1 for Sort by Id
Enter 2 for Sort by Name
Enter 0 for EXIT:
1
List sorted by patientId
Patient [patientId=1, patientName=C]
Patient [patientId=2, patientName=B]
Patient [patientId=3, patientName=A]
Enter 1 for Sort by Id
Enter 2 for Sort by Name
Enter 0 for EXIT:
2
List sorted by patientName
Patient [patientId=3, patientName=A]
Patient [patientId=2, patientName=B]
Patient [patientId=1, patientName=C]
Enter 1 for Sort by Id
Enter 2 for Sort by Name
Enter 0 for EXIT:
0
Exited successfuly


Thanks For Reading , Happy Learning.

Popular Posts

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Today we will see solution for Error In Spring Boot : ***************************  APPLICATION FAILED TO START ***************************  Description: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.  Reason: Failed to determine a suitable driver class. --->My Application.yml : server: port: 8081 spring: datasource: driver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:xe username: sys as sysdba password: root Oracle Version is 21 C Oracle Database 21c Express Edition Release 21.0.0.0.0 - Production Version 21.3.0.0.0. check my pom.xml here : <? xml version = " 1.0 " encoding = " UTF-8 " ?> < project xmlns = " http://maven.apache.org/POM/4.0.0 " xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance " xsi:schemaLocation = " http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/m...

Stream In Java

stream in java 8 : Stream API is used to process collection of objects. stream() method is present in Collection interface from package java.util . Stream is an interface present in java.util package, filter() and map() methods are present in Stream interface. -->when to use filter()  method ? If we want to filter elements from collection based on some boolean condition then we can use filter() method.  for example  : filtering even or odd numbers from list of numbers. -->When to use map()  method ? If we want to create new object for every object in collection then we should use map() method. for example : if we want to increase every number in list by 2 , here every object is getting modified ,we have to use map() in this type of scenario. In below example , we used both filter() and map() methods on stream , inside filter method we applied some condition and in map method we are transforming our object to different one. package com.crtr4u.www; import java...

Class and Object in Java

In Java we have to always deal with objects, now let's understand what is object , how to define object in Java. What is Object In Java ? Object is an entity with STATE and Behavior. Examples of Objects : Bike ,Mobile, Student,Laptop,Car etc. If we consider Bike As Object , Bike Name is state , Bike Color is state , and Running is behavior of Bike,Starting is behavior of bike and stopping is also behavior of Bike. In Java we say , Object is an Instance of class , it means we can create object using class. What is class ? A class is template or blueprint from which objects are created. A class in java can contain fields(variables),Methods(Behaviors),blocks,constructors etc. How To Create class in Java ? Syntax To Create Class :      class College {           String collegeName="COEP";           public void getAdmission(){           System.out.println("In this method we have to wri...