【发布时间】:2017-04-17 03:06:51
【问题描述】:
我有一个简单的代码,我将自定义类对象的列表转换为地图>。 代码如下:
List<NPDto> appList = new ArrayList<NPDto>();
//list gets populated though some other method
//Here is conerting code where i get compile time error
final Map<Integer, List<String>> appMap = appList.stream()
.collect(
Collectors.toMap(
np -> NumberUtils.toInt(np.getPId()),
np -> Arrays.asList(np.getAppsReceived().split(","))
));
// Here is my DTO
public class NPDto {
private String pId;
private String appsReceived;
public String getPId(){
return pId;
}
public void setPId(String pId){
this.pId = pId;
}
public String getAppsReceived(){
return appsReceived;
}
public void setAppsReceived(String appsReceived){
this.appsReceived = appsReceived;
}
}
但是,我收到如下编译器错误:
Type mismatch: cannot convert from Map<Object,Object> to Map<Integer,List<String>>
我正在使用 Java SE 8[1.8.0_91] 进行编译
不知道我错在哪里。有人可以帮忙吗?
【问题讨论】:
-
你们为什么不投票?给我一个理由。
-
不是我的反对意见,但可能是因为您没有向我们展示minimal reproducible example。特别是向我们展示
NPDto中getter 的实际声明。使用不正确的方法名称可能会导致此错误。 -
@greg-449 还添加了 getter 和 setter。
-
您缺少一个右括号(关闭
collect方法调用的那个)。如果这是您的问题中的错字,请包括您正在使用的编译器(javac / Eclipse 的编译器 / ...),知道后者可能在类型推断方面存在问题。使用 javac 1.8.0_102 编译对我来说很好。 -
.. 然后包含您正在使用的编译器。
标签: java java-8 stream java-stream collectors