0

I have two User List objects, merged:

objectList1.addAll(objectList2);

To avoid duplicates converted to a HashSet:

Set<User> users = newHashSet(objectList);

How can I sort the users in ascending order based on First Name?

I tried to use TreeSet, in place of HashSet but that throws Exception.

How can I achieve the result without making the User class to implement Comparable<User>?

Andreas
  • 154,647
  • 11
  • 152
  • 247
Cork Kochi
  • 1,783
  • 6
  • 29
  • 45

1 Answers1

4

Implement the Comparable Interface. https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

Or use a Comparator. https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

Either one should work. The problem is that the Set can't know how to sort itself if it doesn't know how to compare two elements.

Say you want to use Comparator on your User you can define one like this:

Comparator<User> comparator = new Comparator<User>() {
   @Override
   public int compare(User u1, User u2) {
      return u1.name.compareTo(u2.name);
   }
};
Andreas
  • 154,647
  • 11
  • 152
  • 247
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
  • These interfaces have hardly changed, it will still work the same way! – Luka Jacobowitz Feb 12 '16 at 19:49
  • Is there any easy way to move the Hashset to Treeset – Cork Kochi Feb 12 '16 at 19:51
  • Yes, once you've implemented Comparable it should be as easy as this: `Set users = new TreeSet(objectList);` – Luka Jacobowitz Feb 12 '16 at 19:54
  • Is there any other way , I can achieve the result without making user class comparable – Cork Kochi Feb 12 '16 at 20:00
  • Well you could use the Comparator, but you've gotta give the program something to compare two instances, otherwise the program can't know what "ascending order" means in that context. Do you want to order them by their Username? – Luka Jacobowitz Feb 12 '16 at 20:02
  • @CorkKochi Yes, give the `TreeSet` constructor a `Comparator`. That way you won't need to change the `User` class. – Andreas Feb 12 '16 at 20:03
  • @Andreas thats something I am looking for, but I got confused in how can i pass the result object , can you give the code to implement to get a correct idea – Cork Kochi Feb 12 '16 at 20:06
  • @LukaJacobowitz Yes I want to order them by their Username – Cork Kochi Feb 12 '16 at 20:08
  • @ Luka Jacobowitz Thanks a million , the next doubt is , where I will pass the resultObject in this case – Cork Kochi Feb 12 '16 at 20:21
  • You might want to ask another question if you help on a different problem, if this Answer helped you, please upvote and accept the answer. Thanks! – Luka Jacobowitz Feb 12 '16 at 20:23
  • @LukaJacobowitz This link helped me to get the answer in detail which I was searching for , You helped me to reach here http://stackoverflow.com/questions/14154127/collections-sortlistt-comparator-super-t-method-example – Cork Kochi Feb 12 '16 at 20:39