Sort ArrayList using Comparable in Java - Java @ Desk

Friday, May 31, 2013

Sort ArrayList using Comparable in Java














 package test;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class PersonComparable implements Comparable<PersonComparable> {  
      private int age;  
      private String firstName;  
      private String secondName;  
      public int getAge() {  
           return age;  
      }  
      public void setAge(int age) {  
           this.age = age;  
      }  
      public String getFirstName() {  
           return firstName;  
      }  
      public void setFirstName(String firstName) {  
           this.firstName = firstName;  
      }  
      public String getSecondName() {  
           return secondName;  
      }  
      public void setSecondName(String secondName) {  
           this.secondName = secondName;  
      }  
      @Override  
      public int compareTo(PersonComparable personComparable) {  
           int compareAge = ((PersonComparable) personComparable).getAge();  
           return this.age - compareAge;  
      }  
      public static void main(String args[]) {  
           PersonComparable person = new PersonComparable();  
           person.setAge(65);  
           person.setFirstName("Kumar");  
           person.setSecondName("Bhatia");  
           PersonComparable personOne = new PersonComparable();  
           personOne.setAge(35);  
           personOne.setFirstName("Ashish");  
           personOne.setSecondName("Bhambhani");  
           PersonComparable personTwo = new PersonComparable();  
           personTwo.setAge(45);  
           personTwo.setFirstName("Sameer");  
           personTwo.setSecondName("Kulkarni");  
           List<PersonComparable> persons = new ArrayList<PersonComparable>();  
           persons.add(person);  
           persons.add(personOne);  
           persons.add(personTwo);  
           Collections.sort(persons);  
           for (PersonComparable comparable : persons) {  
                System.out.println(comparable.getAge());  
           }  
      }  
 }  






No comments:

Post a Comment