Search code examples
javastringenumscompiler-errorsjava-stream

How cast Enum to String in Stream API?


public class User {
    private String name;
    private Role role;
 }

enum Role {
    ADMIN, MODERATOR, USER
}

List<User> users = Arrays.asList(
                new User("Alex", Role.USER),
                new User("Tom", Role.ADMIN),
                new User("Bob", Role.MODERATOR),
                new User("Mila", Role.USER),
                new User("Kate", Role.MODERATOR)
        );

Map<Role, Long> count = users.stream()
                .collect(Collectors.groupingBy(User::getRole, Collectors.counting()));

Result : {ADMIN=1, USER=2, MODERATOR=2}

I want to group by role and calculate the number of users, using stream API. When I used Map<Role, Long> all is ok.

But I need Map<String, Long> and have a compile error. I don't get how to cast Enum to String in this case?


Solution

  • Use user.getRole().name() instead of only user.getRole().

    name() method will return the name of your defined Enum (eg. ADMIN) in String format.