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

Viewed 79

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.

2 Answers

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)

Make User class implement Comparable interface like this:

public class Test {
    public static void main(String[] args) throws Exception {
        Set<User> set = new TreeSet<>();
        set.add(new User("a", Role.USER));
        set.add(new User("b", Role.MANAGER));
        set.add(new User("c", Role.ADMIN));
        
        System.out.println(set);
    }
}

enum Role{ MANAGER, ADMIN, USER }

class User implements Comparable<User> {
    String userName;
    Role userRole;
    
    public User(String name, Role role) {
        this.userName = name;
        this.userRole = role;
    }
    
    @Override
    public int compareTo(User o) {
        
        return this.userRole.compareTo(o.userRole);
    }
    
    public String toString() {
        return this.userName;
    }
}

Output:

[b, c, a]
Related