Question:
How to sort an ArrayList of objects based on an instance field in Java?
Yeeka
2011-09-28 16:07:57 UTC
I have an ArrayList of objects, each with 3 instance variables:

Name
Number
Position

How can I sort this ArrayList based on the alphabetical order of names, and then print them to the screen? I want to arrange the objects from A-Z. For example if I have three objects - and their respective names are Ben, Chris and Andrew.

I want to arrange them, so I can print each name of each object:

Andrew
Ben
Chris


Thanks for any help out there!
Three answers:
McFate
2011-09-28 16:17:46 UTC
Personally, I would turn them into an array of the object type:



Employee[] emps = myList.toArray( new Employee[ myList.size() ] );



Then you could use Arrays.sort() to sort the array:



Arrays.sort( emps, new Comparator() {

public int compare( Employee a, Employee b ) {

return a.name.compareTo( b.name );

} } );



This is a bit advanced because it uses an anonymous inner type to provide the comparator logic (to cause employees to be sorted by name, it compares on the name field). At the end of this code, emps[] is a sorted list of Employees, sorted by name.
halrosser
2011-09-29 02:56:15 UTC
be sure to implement the Comparable interface -( code a compareTo() method for the object's class) - This is the key - your CompareTo method needs to use the appropriate field to compare to determine which is 'larger' or 'smaller'.

Then use the toArray() method of ArrayList to get an array of that type.

Then use the Array's sort() method.

Then re initialize the ArrayList with the sorted array.
deonejuan
2011-09-29 00:11:19 UTC
You have to implements the Comparable interface, thus write your own .compareTo( Object anotherPerson)



then, cast the incoming Object. Supposing your class def is Person with the three instance vars you show



int compareTo( Object anotherPerson ) {

Person currentPerson = (Person)anotherPerson);

// then you have the vars and methods of the class



return (



String, Integer, Float, Boolean... all the API Objects already have the Comparable written for you


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...