Sort ArrayList using Comparator in Java - Java @ Desk

Saturday, May 18, 2013

Sort ArrayList using Comparator in Java














package test;

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

public class ComparatorImpl {

public static void main(String args[]) {
Person person = new Person();
person.setAge(25);
person.setFirstName("Kumar");
person.setSecondName("Bhatia");



Person personOne = new Person();
personOne.setAge(35);
personOne.setFirstName("Ashish");
personOne.setSecondName("Bhambhani");

Person personTwo = new Person();
personTwo.setAge(45);
personTwo.setFirstName("Sameer");
personTwo.setSecondName("Kulkarni");

List persons = new ArrayList();
  persons.add(person);
  persons.add(personOne);
  persons.add(personTwo);

  Collections.sort(persons, new Comparator() {

   @Override
   public int compare(Object o1, Object o2) {
    // TODO Auto-generated method stub
    return ((Person) o1).getFirstName().compareTo(
      ((Person) o2).getFirstName());
   }

  });

System.out.println("List in ascending order by firstName");
  for (Person person2 : persons) {
   System.out.println("First Name : "+person2.getFirstName());
  }
 }
}







No comments:

Post a Comment