«

»

Jan
26

Java Sorting Objects at Runtime using Comparator

Java gives very convenient way for sorting collection types by Collections.sort method. It have two flavors

  • Collections.sort( collection, new Comparator < T>( )){}
    This is runtime sorting, & you will create an anonymous class implementation and will override Comparator’s compare method and return value -1, 0 , 1.
  • Collections.sort( collection)
    You provide collection whose objects implemented Comparable or Comparator interface and provide overridden method.

Let’s we have Student class as below,

class Student {
	private String	name;
	private Integer	id;
	private String	rollNo;
	private Long	grade;

	//getters & setters
}

Sometimes we want to sort it by name, sometimes by grade & sometimes by rollNo. So we can’t implement Comparable or Comparator to fix the sorting field. We will sort the objects dynamically.

public class JavaTest {
	public static void main( String [ ] args ) {
		List < Student > studentList = new ArrayList < Student >( );
		studentList.add( new Student( "Mark", 5L ) );
		studentList.add( new Student( "John", 3L ) );
		studentList.add( new Student( "Faisal", 6L ) );
		studentList.add( new Student( "Keat", 4L ) );
		Collections.sort( studentList, new Comparator < Student >( ) {
			public int compare( Student student1, Student student2 ) {
				return student1.getGrade( ).compareTo( student2.getGrade( ) );
			}
		} );
		for ( Student student : studentList ) {
			System.out.println( "Student Name: " + student.getName( ) + " : " + student.getGrade( ) );
		}
	}
}

The above class is just a snapshot view, about how we sort a collection runtime, where we need it. We can sort by any field/attribute just by creating anonymous class and changing variable in compare method.  That’s all. C YA Next time with another recipe.

 

VN:F [1.9.14_1148]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.14_1148]
Rating: +1 (from 1 vote)
Java Sorting Objects at Runtime using Comparator, 10.0 out of 10 based on 1 rating

About the author

Faisal Basra

Faisal Basra is an independent consultant, software developer, writer, blogger, speaker, architect and technology leader in Lahore, Pakistan. He has been a professional software developer since 2008, has been writing code since 2006.Having hands on experience of popular Java EE frameworks & technologies like JSF, Spring, Hibernate, Enverse, JPA, Richfaces, Primefaces, JSP/Servlet.Tools & Servers: jUnit, Log4j, Maven, Eclipse, MyEclipse, NetBeans, Tomcat, Jboss, WebLogicMobile Development: Google Android

Permanent link to this article: http://www.javaplex.com/blog/java-sorting-objects-at-runtime-using-comparator/

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>