Comparable Example in Java

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

class Student implements Comparable<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;
	}

	@Override
	public int compareTo(Student stud) {
		// TODO Auto-generated method stub
		return this.studentAge - stud.getStudentAge();
	}
}

public class ComparableExample {

	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 comparable
		Collections.sort(list);

		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 program to get list of all the files from a given directory?
Write a Comparator to compare students based upon their name and age?
Simple Array Sorting Program.
Bubble Sort Example.
Write a java program to check if a number is Armstrong number or not?








Receive Latest Java Examples in Your Email: