0

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 ?

1
  • you need for(Map.Entry<String, ArrayList<String>> m:movieGenres.entrySet()) Commented Oct 28, 2020 at 14:43

2 Answers 2

3

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();
    ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Well, then the first mouthful is the only solution, which fortunately is in the answer, so not sure if that's worth mentioning.
Perhaps adding a note like "If you are using Java 10 or later..." since the OP did not indicate version.
I have java 11.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.