Is there a way to achieve the following example code, leveraging Java Stream API rather than having to create a HashMap and populate it inside double forEaches? I was trying to play around with groupingBy and flatMap but couldn't find a way out.
Having a list of Movies, where each one has a list of genres (Strings)...
class Movie {
List<String> genres;
}
List<Movie> movies = new ArrayList<>();
...I want to group all the movies by genre
Map<String, List<Movie>> moviesByGenre = new HashMap();
movies.stream()
.forEach(movie -> movie.getGenres()
.stream()
.forEach(genre -> moviesByGenre
.computeIfAbsent(genre, k -> new ArrayList<>())
.add(movie)));