Trying to combine two data, one for movies, the other for genres, only if the ids are the same from both properties.
Both got id, name fields, please consider the id in Movie is PK and Genre uses it as FK like below so.
List<Movie> movies = new ArrayList<>();
movies.add(new Movie(1, "Titanic"));
movies.add(new Movie(2, "Batman"));
movies.add(new Movie(3, "Silence of the Lambs"));
movies.add(new Movie(4, "1917"));
movies.add(new Movie(5, "Fight Club"));
movies.add(new Movie(6, "Inception"));
movies.add(new Movie(7, "The Godfather"));
movies.add(new Movie(8, "Peral Harbor"));
List<Genres> genres = new ArrayList<>();
genres.add(new Genres(1, "Drama"));
genres.add(new Genres(4, "Drama"));
genres.add(new Genres(8, "Drama"));
genres.add(new Genres(7, "Drama"));
genres.add(new Genres(2, "Action"));
genres.add(new Genres(5, "Action"));
genres.add(new Genres(6, "SF"));
genres.add(new Genres(3, "Thriller"));
genres.add(new Genres(5, "Thriller"));
genres.add(new Genres(5, "Crime"));
genres.add(new Genres(16, "Comedy"));
genres.add(new Genres(3, "Horror"));
genres.add(new Genres(1, "Disaster"));
genres.add(new Genres(7, "Noir"));
genres.add(new Genres(1, "Romance"));
...
I wanted to tie them together if ids are equals and put genres array.
The result should looke like below:
result: [
{"id": 1, "name": "Titanic", "genres": ["Drama", "Disaster", "Romance"] },
...
{"id": 5, "name": "Fight Club", "genres": ["Action", "Thriller", "Crime"] },
]
Barely got an idea to use stream or maybe not.
Thanks in advance.
Sorry for the rudimentary code (don't have access to my IDE right now), but here's how I would approach it.
First, extend your Movie
class with a list of strings that will hold the genres.
class Movie {
int id;
String name;
List<String> genres;
Movie(int id, String name) {
this.id = id;
this.name = name;
}
}
class Genres {
int id;
String name;
Genres(int id, String name) {
this.id = id;
this.name = name;
}
}
Second, group your list of genres by their IDs:
Map<Integer, List<Genres>> genresGroupedById = genres.stream().collect(Collectors.groupingBy(g -> g.id));
Finally, iterate through your list of movies and assign the appropriate genres like so:
movies.forEach(m -> m.genres = genresGroupedById.get(m.id).stream().map(g -> g.name).collect(Collectors.toList()));
That should get you started to make the code a little bit cleaner. :)