Sort Collection in Java

Tagged:  

Example program showing how to sort ArrayList in Java.

 

//SortArrayList.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class SortArrayList {

	public static void main(String[] args){
		//declare generic ArrayList
		ArrayList<Person> list = new ArrayList<Person>();

		//add person to list
		list.add( new Person("Juan", "Cruz", 16) );
		list.add( new Person("Peter", "James", 14) );
		list.add( new Person("James", "Bond", 16) );
		list.add( new Person("JR", "Galia", 20) );
		list.add( new Person("Jack", "Bauer", 11) );

		
		//sort list of Person according to age
		Collections.sort(list, new Comparator<Person>(){
			public int compare(Person p1, Person p2) {
				if( p1.getAge() < p2.getAge() )
					return -1;
				else if( p1.getAge() > p2.getAge() )
					return 1;
				else
					return 0;
			}
		});
		
		
		//display sorted list
		System.out.println("\n\tFirst Name\tLast " +
				"Name\tAge");
		for( Person p: list ){
			System.out.println("\t"+p.getFirstName() +
				"\t\t" + p.getLastName() + "\t\t" 
				+p.getAge());
		}
		
	}
}


Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.