This discussion is archived
4 Replies Latest reply: Mar 17, 2011 2:26 PM by 830459 RSS

ArrayList Sorting

843793 Newbie
Currently Being Moderated
how do i sort the arrayList acccrding to Employee First Name Or Last Name
Array List having all the element is object of employee class having property first name and last name
sample code is give bellow
import java.util.*;
class hewitt {
     ArrayList al = new ArrayList();
     void check() {
          for (int i = 0; i < 50; i++) {
               employee emp = new employee();
               emp.fname = "" + (int)(Math.random() * 50);
               emp.lname = "" + (int)(Math.random() * 100);
               al.add(emp);
          }
          Collections.sort(al);
          for (int i = 0; i < 50; i++)
          {
               employee e=(employee)al.get(i);
               System.out.print("First -"+e.fname+" Last -"+e.lname+"\n");
          }

     }
     public static void main(String[] args) {
          hewitt obj = new hewitt();
          obj.check();
     }
}
class employee implements Comparable {
     String fname;
     String lname;
     public int compareTo(Object ob)
     {
          return -1;
     }
     
}
  • 1. Re: ArrayList Sorting
    843793 Newbie
    Currently Being Moderated
    See the Comparator interface and the method Collections.sort(List, Comparator).

    ~Cheers
  • 2. Re: ArrayList Sorting
    800357 Newbie
    Currently Being Moderated
    Right now your compareTo method doesn�t make much sense, because it always returns -1. That is, whatever Object you compare your Employee instance to, the instance would always be considered smaller than that Object.

    If you want employees always to be sorted according to last name and then first name, for example, you should implement your compareTo method so that it compares the last name of the employee to the last name of the employee passed in to the compareTo method (you can easily do this using the compareTo method of the String class). If the last name is equal, you would then compare the first name.

    If you want to be able to choose how to sort, you could write a method like:
    public void sortEmployees( List l, int sortmode ) {
         
         if( sortmode == FIRST_NAME)
              //Construct a Comparator that compares employees by first name
              //Pass the List and the Comparator to Collections.sort
         else if( sortmode == LAST_NAME )
              //Construct a Comparator that compares employees by last name
              //Pass the List and the Comparator to Collections.sort
    }
    Hope this helps. Furthermore I suggest you take this topic to the forum on Collections, because the forum in which you�ve posted it now discusses Generics (not meaning miscellaneous).

    Cheers
    Matthijs
  • 3. Re: ArrayList Sorting
    843793 Newbie
    Currently Being Moderated
    ]perfect code for sorting arrayList containing nth number of employee object .
    now the requirement is sort according to employee firstName or Last name
    Eployee Object having property FirstName and last Name

    import java.util.*;
    class Person implements Comparable {
    private String firstName;
    private String lastName;
    public String getFirstName() {
         return firstName;
    }
    public void setFirstName(String firstName) {
         this.firstName = firstName;
    }
    public String getLastName() {
         return lastName;
    }
    public void setLastName(String lastName) {
         this.lastName = lastName;
    }
    public int compareTo(Object anotherPerson) throws ClassCastException {
         if (!(anotherPerson instanceof Person))
         throw new ClassCastException("A Person object expected.");
         String anotherPersonName = ((Person) anotherPerson).getFirstName();
         return this.firstName.compareTo(anotherPersonName);
    }
    }
    class Testing {
    public static void main(String[] args)throws Exception {
         ArrayList al=new ArrayList();
         Person persons = new Person();
         persons = new Person();
         persons.setFirstName("Vishal");
         persons.setLastName("Bhando");
         al.add(persons);
         persons = new Person();
         persons.setFirstName("Shailesh");
         persons.setLastName("Sharma");     
         al.add(persons);
         persons = new Person();
         persons.setFirstName("Prashant");
         persons.setLastName("Kumar");
         al.add(persons);
         persons = new Person();
         persons.setFirstName("Arvind");
         persons.setLastName("Singh");
         al.add(persons);
         System.out.println("Natural Order");
         for(int i=0;i<al.size();i++)
         {
              Person p=new Person();
              p=(Person)al.get(i);
              System.out.print(p.getFirstName()+"\n");
         }
         Collections.sort(al);
         System.out.println();
         System.out.println("Sorted by Name");
         for(int i=0;i<al.size();i++)
              {
                   Person p=new Person();
                   p=(Person)al.get(i);
                   System.out.print(p.getFirstName()+"\n");
              }
         
         
    }

    }
  • 4. Re: ArrayList Sorting
    830459 Newbie
    Currently Being Moderated
    797354 wrote:

    Right now your compareTo method doesn�t make much sense, because it always returns -1. That is, whatever Object you compare your Employee instance to, the instance would always be considered smaller than that Object.



    If you want employees always to be sorted according to last name and then first name, for example, you should implement your compareTo method so that it compares the last name of the employee to the last name of the employee passed in to the compareTo method (you can easily do this using the compareTo method of the String <font face="tahoma,verdana,sans-serif" size="1" color="#000">class</font>). If the last name is equal, you would then compare the first name.



    If you want to be able to choose how to sort, you could write a method like:


    <font color="navy"><b>public</b></font> <font color="navy"><b>void</b></font> sortEmployees( List l, <font color="navy"><b>int</b></font> sortmode ) <font color="navy">{</font>          <font color="navy"><b>if</b></font>( sortmode == FIRST_NAME)          <font color="darkgreen">//Construct a Comparator that compares employees by first name</font>          <font color="darkgreen">//Pass the List and the Comparator to Collections.sort</font>     <font color="navy"><b>else</b></font> <font color="navy"><b>if</b></font>( sortmode == LAST_NAME )          <font color="darkgreen">//Construct a Comparator that compares employees by last name</font>          <font color="darkgreen">//Pass the List and the Comparator to Collections.sort</font><font color="navy">}</font>
    Hope this helps. Furthermore I suggest you take this topic to the forum on Collections, because the forum in which you�ve posted it now discusses Generics (not meaning miscellaneous).



    Cheers

    Matthijs
    Thanks for your analysis! Nice writing.