Assume I have two List
s, one for Movie
s and another one for Genre
s. I want to map one or more Genre
s to one Movie
and/or one or more Movie
s to one Genre
. How would I do that?
Asked
Active
Viewed 56 times
0

LionC
- 3,106
- 1
- 22
- 31

Kuldeep Kumar Sharma
- 11
- 3
-
2Map
> <-- like this – nafas Jun 02 '15 at 10:12 -
@nafas Perhaps you should have written your comment as an answer, with an explanation to future readers? – Luke Jun 02 '15 at 10:14
-
2@Luke answers should be precise where comments can be clue, – nafas Jun 02 '15 at 10:17
4 Answers
0
The Java Map
-interface is used to map objects to other objects. A Map<Movie, List<Genre>>
assigns a List
of Genre
s to a single Movie
, a Map<Genre, List<Movie>>
would do it the other way around.
If you want a 2-way-map, there is already a question for that
0
The collection you should be using is Map<String, List<String>>
.
For mapping one or more genre to a movie, you should use:
Map<movie, List<genre>>
And for mapping one or more movie to a genre, you should use:
Map<genre, List<movie>>

shruti1810
- 3,920
- 2
- 16
- 28
0
I suppose...something like that:
Movie f = new Movie("fight club"); // for example..
List<Genre> genres = ...;
genres.add(new Genre("comic"));
genres.add(new Genre("horror"));
Map <Movie,List<Genre>> movieGenres = new HashMap<Movie,List<Genre>>();
movieGenres.add(f,genres);

Andrea De Gaetano
- 335
- 4
- 16
-
...and don't forget to override hash and equals on your classes! – Andrea De Gaetano Jun 02 '15 at 10:36
0
Using appropriate map implementation.
Map<String, MyObject> map = new HashMap<String, MyObject>();
I suggest you to look at Guava multimap
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("action", "rambo");
multimap.put("action", "terminator");
multimap.put("thriller", "rambo");
System.out.println(multimap.get("action"));
System.out.println(multimap.get("thriller"));

Sheetal Mohan Sharma
- 2,908
- 1
- 23
- 24
-
I have a hard time finding the connection from this answer to the question. Consider explaining a bit further what you mean – LionC Jun 02 '15 at 10:27