我正在尝试从列表创建嵌套地图。使用下面的代码片段,我得到编译时错误


  类型不匹配:无法从中转换
  Map<Object,Map<Object,List<ActorContents>>>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 + "_"))
                                )));


使用的实用方法如下

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


当我如下更改代码时,没有错误并且代码执行。

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 + "_"))
                                )));


您能帮忙找出代码段出什么问题吗

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 + "_"))
                                )));


非常感谢您的协助

最佳答案

我们只考虑内部映射Map<Object,List<ActorContents>>,因为外部映射具有相同的问题。考虑一下:

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


现在,您已经有了一个包含2个不同数据类型键的地图。您要让编译器将其转换为具有特定键类型(Actor)的映射。编译器不知道如何将整数或字符串转换为Actor

我故意没有引用您的代码,因为在阅读我的解释之后,您应该可以自己解决问题。阅读generics教程对您也有好处。

07-28 00:59