Sorting Hashset Object in ascending order

时间:2016-02-12 19:42:00

标签: java sorting collections hashset

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>?

1 个答案:

答案 0 :(得分: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);
   }
};