Reputation: 89
I am writing a function which takes two map as argument
Here is my code
public static Map<String, ArrayList<String> > getFavouriteGenres(Map<String, ArrayList<String> > userMovies, Map<String, ArrayList<String> > movieGenres)
{
Map<String, ArrayList<String>> genreMovies = new HashMap<String, ArrayList<String>>();
for (Map.Entry m:movieGenres.entrySet()){
//ArrayList<String> list = m.getValue();
for (String mov:m.getValue()){
ArrayList<String> l = genreMovies.containsKey(mov) ? genreMovies.get(mov):new ArrayList<String>();
genreMovies.put(mov, l.add(m.getKey()));
}
}
//other implementation
On compilation I am getting following error
StreamingApp.java:17: error: for-each not applicable to expression type
for (String mov:m.getValue()){
^
required: array or java.lang.Iterable
found: Object
StreamingApp.java:19: error: incompatible types: Object cannot be converted to String
genreMovies.put(mov, l.add(m.getKey()));
How to solve it ?
Upvotes: 0
Views: 121
Reputation: 1008
Change
for (Map.Entry m:movieGenres.entrySet()){
TO
for (Map.Entry<String, ArrayList<String>> m:movieGenres.entrySet()){
AND
genreMovies.put(mov, l.add(m.getKey()));
TO
l.add(m.getKey());
genreMovies.put(mov, l);
Upvotes: 1
Reputation: 103263
You are using Map.Entry
as a raw type. That means all generics of it and anything derived from it are also blank. Thus, m.getValue()
returns Object
and not ArrayList<String>
.
The solution is to add the generics appropriately:
for (Map.Entry<String, ArrayList<String>> m : movieGenres.entrySet()) {
List<String> list = m.getValue();
...
}
that's a mouthful. Fortunately, you can write that a lot more simply:
for (var m : movieGenries.entrySet()) {
List<String> list = m.getValue();
...
}
Upvotes: 3