-1

Possible Duplicate:
Java sort problem by two fields

I have user object like

class user
{
    String firstName;
    String lastName;
}

I have a List which contains these object , I have to sort it by first name and if first name matches the sort only those name by last name .

Community
  • 1
  • 1

2 Answers2

2

There are a couple of approaches here.

You can to implement a Comparator, and then use this in the standard Java Collection lib to sort your collection e.g. Collections.sort()

Comparator<MyObject> comparator = ....
Collections.sort(listOfObjects, comparator); // note-  will sort in place

An alternative is for your object to implement Comparable. This then introduces a native sort order to your object.

Note that you can implement both approaches simultaneously. The former is useful when you want to implement different sorting strategies (e.g. by name, by date, by size etc.). The latter is useful if you want to make use of the concept of native ordering and the standard sort functions within the Java lib.

Check out the Java tutorial on Object Ordering

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

If you implement Comparable and use your own compareTo method that does what you need.

Another option is to use a custom Comparator as indicated in many other answers.

A nice article showing both approaches can be found here.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176