Happy Lemon
Happy Lemon

Reputation: 95

Use Java 8 stream to convert enum to set

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?

Upvotes: 6

Views: 5847

Answers (3)

marknorkin
marknorkin

Reputation: 4064

You can use EnumSet implementation for this purpose e.g.

For obtaining the Set of Movies:

Set<Movies> movies = EnumSet.allOf(Movies.class);

For obtaining only movies ids:

Set<Integer> moviesIds = movies.stream().map(Movies::getId).collect(Collectors.toSet());

Upvotes: 4

Vinay Prajapati
Vinay Prajapati

Reputation: 7504

If you are able to get stream of Enum values then rest could easily be achieved.

You could use custom Collector impl (My favorite of all time), see example below of a custom collector:-

 Set<Integer> movieIds = Arrays
                .stream(Movies.values())
                .collect(
                         HashSet::new,
                         (set, e) -> set.add(e.getId()),
                         HashSet::addAll
                );

Or you could use map to fetch ids only and the collect to collect these ids to a Set as usual.

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

Upvotes: 4

spinlok
spinlok

Reputation: 3661

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());

Upvotes: 3

Related Questions