Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

sort based on the String - compare..compareTo() ?  RSS feed

 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to sort Employee object based on the city ?


 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this a question or a blurb to demonstrate how its done using Collections#sort and a Comparator?
 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Employee Object is not sorted based on the city. How to do that ?
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kri shan wrote:Employee Object is not sorted based on the city. How to do that ?



 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First you need equals() and hashcode() methods in the Employee class.

Then your current sort method (Collections#sort) should work.

Separating out the comparator into its own class can make your code easier to understand and read.
 
vipul bondugula
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should write an EmployeeComparator<Employee> class which implements Comparator interface comparing city values. Then pass  EmployeeComparator object as one of the parameters to Collections.sort(employeeeList,new EmployeeComparator());. Let me know if this is n't working for you.
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's see if we can't write that in Java8.Now, all you have to do is create a λ and that code will work nicely Also try this:-
Collections.sort(employerList, aDifferentLambda);

Remember: Java8+ only.
 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using Java 7, not Java 8
 
vipul bondugula
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you given a try of what I said. Please do the same and let me know if you have any doubts. Thanks.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!