It's not a secret anymore!
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

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: 10825

Recommended reading
Scroll down to the Comparator section.

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

Joined: Nov 24, 2005
Posts: 14688

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
I agree. Here's the link:
subject: how to sort this list ?
It's not a secret anymore!