![](/img/trans.png)
[英]ERROR: Type mismatch: cannot convert from Map<Object,List<Object>> to Map<String,List<>>
[英]Type mismatch: cannot convert from Map<Object,Map<Object,List<ActorContents>>> to Map<Actor ,Map<String,List<ActorContents>>>
我正在嘗試從列表創建嵌套地圖。 使用下面的代碼片段,我得到編譯時錯誤
類型不匹配:無法從
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
。
我故意沒有引用您的代碼,因為在閱讀我的解釋后,您應該可以自己解決問題。 閱讀泛型教程也對您有好處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.