aspose file tools*
The moose likes Beginning Java and the fly likes how to sort this list ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to sort this list ?" Watch "how to sort this list ?" New topic
Author

how to sort this list ?

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
I have a list of objects. each object is of type

class {
String name;
int id;
String address;
}

how do I sort the list by name then by id ? i.e. these two object have same names then sort by their id. This is like SQL's "order by name, id"

Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10523
    
    9

Recommended reading http://java.sun.com/docs/books/tutorial/collections/algorithms/index.html
Scroll down to the Comparator section.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

By list, you mean the java.util.List interface ?
You can use the java.util.Collections.sort method, and either make your class implement the Comparable interface, or make a Comparator class and pass ot to the sort method. You'll find a detailed explanation here.


[My Blog]
All roads lead to JavaRanch
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: how to sort this list ?