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"); Listpersons = 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()); } } }
Saturday, May 18, 2013
Sort ArrayList using Comparator in Java
Tags
# Core Java
# Java Collection
About Unknown
Kumar Bhatia is a technical resource working with Accenture and owns this blog on Java.
Java Collection
Labels:
Core Java,
Java Collection
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment