• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to do a Comparator with two properties ?  RSS feed

 
majid nakit
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
majid nakit
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I did this :

 
Paul Clapham
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay. Then what results did you get, and what results did you expect, and how do those differ?
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why have you got gender as a String rather than an enum member or similar?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does the rest of your program look like? Maybe you're not calling the sorting code correctly.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!