Use Java 8 stream to convert enum to set
Asked Answered
G

3

6

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?

Grecism answered 13/3, 2018 at 3:7 Comment(0)
U
4

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()); 
Untangle answered 13/3, 2018 at 7:48 Comment(0)
D
4

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());
Dry answered 13/3, 2018 at 7:54 Comment(0)
Q
3

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());
Qintar answered 13/3, 2018 at 4:42 Comment(1)
EnumSet.allOf() is really nice to use. Thanks!Untangle

© 2022 - 2024 — McMap. All rights reserved.