Results 1 to 10 of 10
  1. #1
    megabull is offline Member
    Join Date
    Aug 2012
    Posts
    22
    Rep Power
    0

    Default How to sort firstname, lastname, age in collections list

    I want to sort the elements in the order of firstname, lastname, age. For example, if there are two people with same first name, then the list be sorted by lastname. If both the firstname and lastname are the same, then sorting may be done on the basis of age in ascending order.

    Java Code:
    import java.util.*;
    
    class Employee implements Comparable<Employee> {
    
    	public String name, Lastname;
    	public int age;
    	
    	 public Employee(String name, String Lastname,int age ){
    	     this.name=name;
    	     this.Lastname=Lastname;
    	     this.age=age;
    	 }
    	 
    	 public String getName(){
    		    return name;
    		  }
    	 public String getLastname(){
    		    return Lastname;
    		  }
    		  public int getAge(){
    		    return age;
    		  }
    	
    public int compareTo(Employee obj) {
    	Employee e = (Employee)obj;
    
    if(this.name.equals(e.getName()))
    	{
    		return this.Lastname.compareTo(e.getLastname());
    	}
    	else
    	{
    		return this.name.compareTo(e.getName());
    	}	
    	
    
    }
    	
    public static void main(String arg[]){
    
    	List<Employee> myList = new ArrayList<Employee>();
    myList.add(new Employee("Andrew","Anderson",45));
    myList.add(new Employee("Robert","Stalling",22));
    myList.add(new Employee("Andrew","Anderson",19));
    myList.add(new Employee("Harish","Samtani",45));
    
    
    for(Employee employee : myList){
    	 System.out.println(" "+employee.getName() +" "+employee.getLastname()+ " " + employee.getAge());
    }
    
    
    System.out.println("\nSorting starts now \n");
    
    Collections.sort( myList);
    for(Employee employee : myList){
    	 System.out.println(" "+employee.getName() +" "+employee.getLastname()+ " " + employee.getAge());
    }
    }
    	 
    }


    Current output is
    Andrew Anderson 45
    Robert Stalling 22
    Andrew Anderson 19
    Harish Samtani 45

    Sorting starts now

    Andrew Anderson 45
    Andrew Anderson 19
    Harish Samtani 45
    Robert Stalling 22

    Any suggestions how to sort in order of age in case both first and last names are a match?
    Last edited by megabull; 09-14-2012 at 09:56 AM. Reason: Added current output
    Tools of Choice : Eclipse Helios | Windows Vista | Windows 7 | MySQL | Apache Tomcat

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,663
    Blog Entries
    7
    Rep Power
    21

    Default Re: How to sort firstname, lastname, age in collections list

    You're on the right track; you just have to complete your compareTo( ... ) method; something like this:

    Java Code:
    public int compareTo(Employee that) {
       int result;
       if ((result= this.first.compareTo(that.first)) != 0) return result;
       if ((result= this.last.compareTo(that.last)) != 0) return result;
       return this.age-that.age;
    }
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    makpandian's Avatar
    makpandian is offline Senior Member
    Join Date
    Dec 2008
    Location
    Chennai
    Posts
    450
    Rep Power
    6

    Default Re: How to sort firstname, lastname, age in collections list

    Awesome code JosAH... Thanks a lot..
    Mak
    (Living @ Virtual World)

  4. #4
    megabull is offline Member
    Join Date
    Aug 2012
    Posts
    22
    Rep Power
    0

    Default Re: How to sort firstname, lastname, age in collections list

    @jos : Tried, dint work. My initial code was something like this

    Java Code:
    int res;
    	if(res=(this.name.compareTo(e.getName()))!=0)
        {
            return this.Lastname.compareTo(e.getLastname());
        }
        else
        {
            return this.name.compareTo(e.getName());
        }

    It gave a "Unresolved compilation problem:
    The operator != is undefined for the argument type(s) boolean, int" issue.
    Last edited by megabull; 09-14-2012 at 10:39 AM.
    Tools of Choice : Eclipse Helios | Windows Vista | Windows 7 | MySQL | Apache Tomcat

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,097
    Rep Power
    20

    Default Re: How to sort firstname, lastname, age in collections list

    That code is not the same (structure-wise) as Jos' code above.
    Jos does not use the equals() method.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: How to sort firstname, lastname, age in collections list

    Quote Originally Posted by megabull View Post
    Java Code:
    int res;
    if(res = (this.name.equals(e.getName())) != 0)
    Use horizontal whitespace for readability (not that it helps very much in this particular code line). See Code Conventions for the Java Programming Language: Contents

    What exactly are you trying to compare in that if condition? Why are you trying to assign an int to this.name.equals(e.getName())? Does that method call return an int value?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  7. #7
    megabull is offline Member
    Join Date
    Aug 2012
    Posts
    22
    Rep Power
    0

    Default Re: How to sort firstname, lastname, age in collections list

    @Tolls : My bad. I had typed the code by modifying the code i posted previously, so missed replacing the equals with compareTo
    Tools of Choice : Eclipse Helios | Windows Vista | Windows 7 | MySQL | Apache Tomcat

  8. #8
    megabull is offline Member
    Join Date
    Aug 2012
    Posts
    22
    Rep Power
    0

    Default Re: How to sort firstname, lastname, age in collections list

    @Db : Yes,the function returns an integer value (see line 24 of the original post ). What i want to do is that check the int condition after the string condition stops working. I tried the following code, but it failed to work

    Java Code:
    if(this.name.equals(e.getName()))
    	{
    		if(this.Lastname.equals(e.getLastname()))
    				{
    			return (this.age.compareTo(e.getAge()));
    				}
    		else
    			{
    			return this.name.compareTo(e.getLastname());
    			}
    	}
    	else
    	{
    		return this.name.compareTo(e.getName());
    	}

    It shows the following error

    Cannot invoke compareTo(int) on the primitive type int
    on the
    Java Code:
     return this.age.compareTo(e.getAge()));
    line
    Tools of Choice : Eclipse Helios | Windows Vista | Windows 7 | MySQL | Apache Tomcat

  9. #9
    megabull is offline Member
    Join Date
    Aug 2012
    Posts
    22
    Rep Power
    0

    Default Re: How to sort firstname, lastname, age in collections list

    got it. Declaring as int was the issue. Should have declared it as integer.
    Tools of Choice : Eclipse Helios | Windows Vista | Windows 7 | MySQL | Apache Tomcat

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,097
    Rep Power
    20

    Default Re: How to sort firstname, lastname, age in collections list

    Again, see the code Jos wrote.
    That shows what he did for 'age'.

    Second, you've a typo (or copy and paste error) on this line:
    Java Code:
    return this.name.compareTo(e.getLastname());
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Collections sorting a list made of generic class objects
    By andreiutz10 in forum New To Java
    Replies: 5
    Last Post: 02-07-2012, 05:56 PM
  2. Problem arraylist result when use Collections.sort
    By i4ba1 in forum Advanced Java
    Replies: 4
    Last Post: 02-09-2011, 08:00 AM
  3. Collections.sort()
    By collin389 in forum Advanced Java
    Replies: 11
    Last Post: 12-31-2009, 11:03 AM
  4. Collections Sort
    By senthil_jr in forum Advanced Java
    Replies: 2
    Last Post: 06-04-2008, 08:11 AM
  5. How to sort a list using Bubble sort algorithm
    By Java Tip in forum Algorithms
    Replies: 3
    Last Post: 04-29-2008, 08:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •