| Author |
How to do a Comparator with two properties ?
|
majid nakit
Ranch Hand
Joined: Jun 26, 2001
Posts: 160
|
|
Hi,
I have a class :
I would like to create a comparator :by Gender (Female before Male), then Last Name ascending
Please your help is appreciated.
thanks
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
majid nakit wrote:I would like to create a comparator :by Gender (Female before Male), then Last Name ascending
okay. So what problem are you having ? What have you tried ?
|
Joanne
|
 |
majid nakit
Ranch Hand
Joined: Jun 26, 2001
Posts: 160
|
|
Hi,
I did this :
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
|
Okay. Then what results did you get, and what results did you expect, and how do those differ?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
|
Why have you got gender as a String rather than an enum member or similar?
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
|
What does the rest of your program look like? Maybe you're not calling the sorting code correctly.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
majid nakit wrote:I did this:
...
This is what I got:...
Well, I don't see anything wrong with your compare() method, so Jesper's advice might be worth looking into.
Just FYI: You can reduce your code a little with the ternary operator, viz:
int ret = a.getGender().compareTo(b.getGender());
return ret == 0 ? a.getLastname().compareTo(b.getLastname()) : ret;
but it's just a style thing; what you have is perfectly fine.
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
 |
|
|
subject: How to do a Comparator with two properties ?
|
|
|