javaenumsjava-stream

How to limit user to choose just two enums from list using Java Streams?


I have an enum class from which user can choose up to 2 options. If he chooses more than 2 an error message should be displayed.

I would like to do this using Java streams. I am still trying to figure out how they work.

So far I came up with this piece of code under:

public enum UserSkills {

    HARD_WORKNG("HARD_WORKNG"),
    ON_TIME("ON_TIME"),
    HONEST("HONEST");

    public final String value;

    UserSkills(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return name() + "[" + value + "]";
    }

    public static List < UserSkills > of (String userSkills) {
        notNull(userSkills, "userSkills cannot be null");
        return Arrays.stream(values())
            .flatMap(s - > {
                if (values().length > 3) {
                    throw new IllegalArgumentException(String.format("you can only choose up to 3 user skills", userSkills));
                } else {

                }
            }).collect(Collectors.toList());
    }
}

I am not sure how to finish it any advice appreciated.


Solution

  • It seems that the method of should accept a vararg String ... userSkills (or the input String should be split somehow to identify multiple enum values):

    public static List<UserSkills> of (String ... userSkills) {
        List<UserSkills> result = Arrays.stream(userSkills)
            .filter(Objects::nonNull)
            .map(UserSkills::valueOf) // throws IllegalArgumentException no enum constant
            .distinct()
            .collect(Collectors.toList());
            
        if (result.size() > 2) {
            throw new IllegalArgumentException("Only 2 skills can be selected");
        }
        return result;
    }
    

    Test:

    List<UserSkills> skills = UserSkills.of(null, "HARD_WORKNG", "HONEST", "HARD_WORKNG", "ON_TIME");
    
    Exception in thread "main" java.lang.IllegalArgumentException: Only 2 skills can be selected
    
    List<UserSkills> skills = UserSkills.of(null, "HARD_WORKNG", "HONEST", "HARD_WORKNG");
    System.out.println(skills);
    

    Output:

    [HARD_WORKNG[HARD_WORKNG], HONEST[HONEST]]