This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Sorting an arraylist of arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting an arraylist of arrays" Watch "Sorting an arraylist of arrays" New topic

Sorting an arraylist of arrays

Stuart Forbes

Joined: Apr 26, 2005
Posts: 1
I have an ArrayList, which contains X amount of String[]s. Each string array has stuff like Name, Surname, Address, Town, etc.

I want to be able to sort the ArrayList of arrays, by a specified entry in each array. name, or surname, or... etc. I assume there would be a sort method, which would take a parameter searchBy or something like that.

What would be the best way to do this?

Thanks in advance for any help.
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

I assume you can guarentee the ordering of you String arrays? So you know that surname is always element 2 for example?

What you could do is write a Comparator which has an extra property which represents the element in your String array you want to use to sort your List by. Then you could use Collections.sort(List list, Comparator c).
[ April 26, 2005: Message edited by: Paul Sturrock ]

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Lionel Badiou
Ranch Hand

Joined: Jan 06, 2005
Posts: 140
Hello Stuart,

You might try to:
1- Write your own Comparator (that compares two entries in your ArrayList)
2- Use Collections.sort(myArraylist, myComparator)

You may find details on Comparator

Best regards,

Lionel Badiou
CodeFutures Software
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Sorting an arraylist of arrays