简体   繁体   中英

Type mismatch: cannot convert from Map<Object,Map<Object,List<ActorContents>>> to Map<Actor ,Map<String,List<ActorContents>>>

I am trying to create nested map from a list. With the below snippet I get compile time error

Type mismatch: cannot convert from Map<Object,Map<Object,List<ActorContents>>> to Map<Actor,Map<String,List<ActorContents>>>

 Map<Actor, List<String>> actorTypeOfContents = typeofContentforActor(genres, genreId);

            Map<Actor, Map<String, List<ActorContents>>> imageMap1=                 
                actorContents.stream()
                        .collect(Collectors.groupingBy(e -> e.getActor(), Collectors.groupingBy( p -> Utility.find(actorTypeOfContents.get(p.getActor()), i -> StringUtils.contains(p.getName(), "_" + i + "_"))
                                ))); 

Utility method used is as below

public static <T> T find(List<T> items, Predicate<T> matchFunction) {
        for (T possibleMatch : items) {
            if (matchFunction.test(possibleMatch)) {
                return possibleMatch;
            }
        }
        return null;
    }

When I change the code as below There is no error and code executes.

List<String> actorNames =actorTypeOfContents.get(Actor.Genre1);

Map<Actor, Map<String, List<ActorContents>>> imageMap1=                 
                actorContents.stream()
                        .collect(Collectors.groupingBy(e -> e.getActor(), Collectors.groupingBy( p -> Utility.find(actorNames, i -> StringUtils.contains(p.getName(), "_" + i + "_"))
                                ))); 

Could you help to figure out what is wrong with the snippet

Map<Actor, Map<String, List<ActorContents>>> imageMap1=                 
                actorContents.stream()
                        .collect(Collectors.groupingBy(e -> e.getActor(), Collectors.groupingBy( p -> Utility.find(actorTypeOfContents.get(p.getActor()), i -> StringUtils.contains(p.getName(), "_" + i + "_"))
                                ))); 

Your assistance is highly appreciated

Lets consider the inner map Map<Object,List<ActorContents>> only, since the outer has the same issue. Consider this:

Map<Object,List<ActorContents>> map = new HashMap<>();
map.put(1, Arrays.asList(new ActorContents()));
map.put("one", Arrays.asList(new ActorContents()));

Now, you've a map with 2 keys that are different data types. You're asking the compiler to convert it into a map with a specific type for the key ( Actor ). The compiler doesn't know how to convert an integer or a string to an Actor .

I deliberately didn't reference your code because after reading my explanation, you should be able to figure out the problem yourself. It'll also do you good to read the generics tutorial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM