Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Java 8 stream to convert enum to set

Tags:

stream

java-8

I have an enum looks like:

public enum Movies {
SCIFI_MOVIE("SCIFI_MOVIE", 1, "Scifi movie type"),
COMEDY_MOVIE("COMEDY_MOVIE", 2, "Comedy movie type");

private String type;
private int id;
private String name;

Movies(String type, int id, String name) {
    this.type = type;
    this.id = id;
    this.name = name;
}

public int getId() {
    return id;
}

}

I know that I can use stream to create a Set of Movies enum with:

Set<Movie> Movie_SET = Arrays.stream(Movie.values()).collect(Collectors.toSet());

What if I want to create a Set of enum Movies id. Is there a way to do that with stream?

like image 892
Happy Lemon Avatar asked Jan 28 '23 12:01

Happy Lemon


1 Answers

Yes, assuming you have a getter for your id, your Movies enum might look like this:

public enum Movies {
    SCIFI_MOVIE("SCIFI_MOVIE", 1, "Scifi movie type"),
    COMEDY_MOVIE("COMEDY_MOVIE", 2, "Comedy movie type");

    private String type;
    private int id;
    private String name;

    Movies(String type, int id, String name) {
        this.type = type;
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }
}

Then, you can get the set of ids by using Stream.map():

Set<Integer> movieIds = Arrays.stream(Movies.values()).map(Movies::getId)
    .collect(Collectors.toSet()); 

BTW, an alternative way to create the set of all movies is to use EnumSet.allOf():

Set<Integer> movieIds = EnumSet.allOf(Movies.class).stream().map(Movies::getId)
    .collect(Collectors.toSet());
like image 199
spinlok Avatar answered Jan 31 '23 02:01

spinlok