This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes How to do a Comparator with two properties ? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "How to do a Comparator with two properties ?" Watch "How to do a Comparator with two properties ?" New topic
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
    
    9
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
    
    2

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
    
    4
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
    
    3

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
    
    7

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?
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: How to do a Comparator with two properties ?
 
Similar Threads
"this" in constuctor problem
problems comparing two people for a dating agency program
syntax error
Object arrays?
Storing Enum Types