• Entries (RSS)
  • Comments (RSS)

Sorting an ArrayList of objects.

Posted by | Posted in Java | Posted on 16-10-2008

Tagged Under :

Sorting an ArrayList of objects.

How do we sort an ArrayList of objects? The easiest way to sort an ArrayList of Objects is to use the Collections.sort() method. But how does the sort method know based on which field you need to sort? The solution is to implement the Comparator interface and override the compare method. For e.g.: if I have a class named person with the following structure.

class Person {
    private String firstName;
    private String lastName;
 
    public Person(){
    }
    public Person(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }
 
    /**
     * @return Returns the firstName.
     */
    public String getFirstName() {
        return firstName;
    }
    /**
     * @param firstName The firstName to set.
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    /**
     * @return Returns the lastName.
     */
    public String getLastName() {
        return lastName;
    }
    /**
     * @param lastName The lastName to set.
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public String toString(){
        return "## Firstname : "+this.firstName+", Lastname : "+this.lastName;
    }
}

I have created some objects of Person class and they are added to an ArrayList. Now I need to sort the ArrayList based on Person’s firstName. The complete code listing for sorting the ArrayList is given below.

	Person p = new Person("Bruce", "Willis");
        Person p1  = new Person("Tom", "Hanks");
        Person p2 = new Person("Nicolas","Cage");
        Person p3 = new Person("John","Travolta");
 
        ArrayList list = new ArrayList();
        list.add(p);
        list.add(p1);
        list.add(p2);
        list.add(p3);
 
        Collections.sort(list, new Comparator(){
 
            public int compare(Object o1, Object o2) {
                Person p1 = (Person) o1;
                Person p2 = (Person) o2;
               return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
            }
 
        });
 
        System.out.println(list);

Here inside my Collections.sort method I am implementing the Comparator interface and overriding the compare method.

Share

Read More

Comments

50 comments posted onSorting an ArrayList of objects.

  1. Thanks.

  2. Thanks alot for this. You saved me ALOT of time.

    Cheers,
    NJ

  3. Very helpful!

    Thanks.

  4. Wonderful!

    Thanks!

  5. Thanks Albin!!

  6. Thank you!

  7. Great!

  8. In this code, you have applied sorting based on firstName attribute only. How do you sort for two or more attributes. say either firstName or LastName or id?

  9. thanks a lot dear it is very helpfull

  10. Thank you dear it will help me a lot …

  11. public Person(String firstName, String lastName){
    this.firstName = firstName;
    this.lastName = lastName;

    Bad technique!
    Your formal and informal parameters should have different names to avoid confusion

  12. Nice example. Look for concept.. Not technique

  13. Thank you very much.
    you save me from head ache of lot coding
    and also time.
    Actually want to say thanks..

  14. thanks a lot ))) it is a great feature !

  15. Many thanks. Worked fine with me in an array of objects with different variables

  16. Good Example. Saved a ton of time. Thanks.

  17. Good demonstration.
    Thanks a lot!

  18. OH YEAAAH! That’s what I was looking for! Many THX

  19. wahhhhh.. thank you very much… you really saved my life . this is what i am trying to understand.. thanx for the help. ;)

  20. Thanks dude, nice tip !

  21. Is there a way to do this with multiple items in the object?

    For your example: Let’s say we also have middle name in there. That means if we add Bruce K Willis before Bruce A Willis, then it will technically be out of order.

    I ask this because I am running into an issue like that right now. Do you know of a good way to do that?

  22. thanks, it was very helpful

  23. this library can be used for dynamic list sorting

    http://code.google.com/p/list-sorter/

  24. @Tamer, thank you for the library. But do we need another dependency for doing such a simple operation?

  25. Excellent, straightforward and easy to understand demonstration! Thank you so much, seeing this saved me who knows how much time!

  26. Keep It Up! This example really helped in at a critical time.
    May Allah’s Blessing upon you.

  27. Nice Example

  28. Very Nice, thats !

  29. Excellent example, easy to follow, thank you!

  30. Thank’s, very helpfull

  31. Thanks,very helpful.Easy to implement…

  32. yes really it was very nice..i was looking for this concept for long time…at lost i found here…could you please elaborate more about comparator interface…

  33. file contains key and values
    how to modify the file data without using resource bundle(properties class)

  34. Thank you very much for this help.

  35. A good example to implement.

  36. A good example to implement sorting.
    Thanks

  37. How would I do something like this?

    Sort my ArrayList in A-Z order.
    Sort my ArrayList in number order.

  38. You need to change the logic in your compareTo method for this.

  39. how to update text file data using File Stream class

  40. Nice one :)

  41. Thank you very much !
    Very helpful indeed !

  42. Great example..saved a lot of my time… :)

  43. Thanks….

  44. Thank you very much :D

  45. This is so awesome thanks. It worked for me :) :)

  46. Can you help me to do this one?

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    public class confusing;

    public static void main(String[] args) {

    String A[] = { “Joseph”,”Ariana”,”Xena”,”Rene”,”Peter”,”Diana”,
    “Rihanna”};
    String B[] = {“Madona”,”Diddy”,”Joe”,”Alice”};

    List list = new ArrayList(Arrays.asList(A));
    list.addAll(Arrays.asList(B));
    Object[] C = list.toArray();

    System.out.println(Arrays.toString(C));

    }
    }

    How i can sort it using copreTo method like this?

    for(int j = 0; j < C.length; j++) {
    for(int i = j + 1; i < C.length; i++) {
    if(C[i].compareToIgnoreCase(C[j]) < 0) {
    String K = C[j];
    C[j] = C[i];
    C[i] = K;
    }
    }
    System.out.println(C[j]);

    }
    }

  47. Wonderful! It helped me a lot Thanks :)

  48. Very comprehensible.. thanks

  49. Thanks for the help….

  50. Thank you! This saved me a LOT of time!

Post a Comment