Sort List of Collections in Java using Comparable interface

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances.

Example

class Movie implements Comparable<Movie> {
	String name;
	int stars;
	int year;

	public Movie(String name, int stars, int year) {
		this.name = name;
		this.stars = stars;
		this.year = year;
	}

	@Override
	public int compareTo(Movie o) {
		return  o.stars - this.stars;
	}

	@Override
	public String toString() {
		return "Movie [name=" + name + ", stars=" + stars + ", year=" + year + "]";
	}
}

public class SortWithCollections {
	public static void main(String[] args) {

		List<Movie> m = new ArrayList<Movie>();
		m.add(new Movie("Alam Ara", 1, 1970));
		m.add(new Movie("Raja", 3, 2007));
		m.add(new Movie("Rani", 4, 2001));

		Collections.sort(m);

		for (Movie mm : m) {
			System.out.println(mm.toString());
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *