How to sort a set of objects according to Enum field in java

guess we have enum like this

enum Role{ MANAGER, ADMIN, USER }

and also we have class

public class User{
     String userName;
     Role userRole;
}

then we have Set of users. I want to sort this user Set according to role enum. Users with role as MANAGER must come first and users with the USER Role must go to the end of the set.

Answer

Assuming you have the values in a list called yourList. Of course you can add to the set directly, if that fits your needs better.

SortedSet<User> set = new TreeSet<User>(Comparator.comparing(User::userRole)
   .thenComparing(User::userName));
set.addAll(yourList)

Leave a Reply

Your email address will not be published. Required fields are marked *