5

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?

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
Happy Lemon
  • 85
  • 1
  • 5

3 Answers3

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());
Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
spinlok
  • 3,561
  • 18
  • 27
3

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()); 
Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
3

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());
marknorkin
  • 3,904
  • 10
  • 46
  • 82