22
Nov

List sort with custom objects

Sort a list of custom objects:
=================================

Sort a list of primitive data, can be quickly achieved via 

	Collections.sort(myList);

		List<String> myList = new ArrayList<>();
		myList.add("Ram");
		myList.add("John");		
		myList.add("Crish");		
		myList.add("Tom");		
		
		Collections.sort(myList);
		System.out.println(myList);




In order to sort, list of objects (say Objects of Employee class) 


public class Employee {

	private String Name;
	private int age;

	// getters/setters for Name and age

	// Constructor to initialize Name and age
}


List<Employee> myList = new ArrayList<>();
myList.add(new Employee("Anna", 39));
myList.add(new Employee("Zara", 38));
myList.add(new Employee("Debbie", 37));


Collections.sort(myList) is not supported in Java.  and following error is observed:

The method sort(List<T>) in the type Collections is not applicable for the arguments (List<Empl>)


In order to sort such lists, following steps needs to be followed

Step 1: create your custom comparator which accepts Employee objects as follow:
=================================================================================

import java.util.Comparator;

class MyAgeComp implements Comparator<Empl> {

	@Override
	public int compare(Empl e1, Empl e2) {
		if (e1.getAge() < e2.getAge()) {
			return -1;
		} else {
			return 1;
		}
	}
}


Step 2: In your main(), use above custom comparator class

	Collections.sort(myList, new MyAgeComp());






Full code:

Step 1:  Employee class structure:
===================================

public class Empl {

	private String Name;
	private int age;

	// getters/setters

	// constructor to initialize data and enable storage with list
	public Empl(String name, int age) {
		this.Name = name;
		this.age = age;
	}

}


Step 2: your comparator which accepts above class for comparison
==================================================================

import java.util.Comparator;

class MyAgeComp implements Comparator<Empl> {

	@Override
	public int compare(Empl e1, Empl e2) {
		if (e1.getAge() < e2.getAge()) {
			return -1;
		} else {
			return 1;
		}
	}
}

Step 3: your main program 
============================


		List<Empl> list = new ArrayList<Empl>();
		list.add(new Empl("Ram", 3000));
		list.add(new Empl("John", 6000));
		list.add(new Empl("Crish", 2000));
		list.add(new Empl("Tom", 2400));
		Collections.sort(list, new MyAgeComp());
		System.out.println("Sorted list entries: ");
		for (Empl e : list) {
			System.out.println(e.getName() + "\t"+ e.getAge());
		}

Output:

Sorted list entries: 
Crish	2000
Tom	2400
Ram	3000
John	6000