Comparator Example in Java

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

class Student implements Comparator<Student> {

	private String studentName;
	private int studentAge;

	Student() {
	}

	Student(String name, int age) {
		this.studentName = name;
		this.studentAge = age;
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public int getStudentAge() {
		return studentAge;
	}

	public void setStudentAge(int studentAge) {
		this.studentAge = studentAge;
	}

	// Overriding the compare method to sort with age
	public int compare(Student stdtn1, Student stdtn2) {
		return stdtn1.studentAge - stdtn2.studentAge;
	}
}

public class ComparatorExample {

	public static void main(String args[]) {

		// Create student objects with name and age
		Student student1 = new Student("John", 38);
		Student student2 = new Student("Ram", 21);
		Student student3 = new Student("Shyam", 18);
		Student student4 = new Student("Arun", 28);

		// Creating a list takes list of Student objects
		List<Student> list = new ArrayList<Student>();
		list.add(student1);
		list.add(student2);
		list.add(student3);
		list.add(student4);
		
		System.out.println("Before Sorting: ");
		// Before Sorting printing list.
		for (Student s : list) {
			System.out.print(s.getStudentName() + ":" + s.getStudentAge()
					+ ", ");
		}

		// Here it Sorts the arrayList using comparator
		Collections.sort(list, new Student());

		System.out.println("\nAfter Sorting : ");
		// After Sorting printing list
		for (Student s : list) {
			System.out.print(s.getStudentName() + ":" + s.getStudentAge()
					+ ", ");
		}
	}
}
Output
Before Sorting: John:38, Ram:21, Shyam:18, Arun:28, After Sorting : Shyam:18, Ram:21, Arun:28, John:38,












Related Examples


Write a Comparable to compare students based upon their age?
Simple Array Sorting Program
Write a program to convert from decimal to binary?
Write a program to get list of all the files from a given directory?
Producer Consumer Example in Thread
Write a program to reverse a String?
Write a Comparator to compare students based upon their name and age?








Receive Latest Java Examples in Your Email: