【问题标题】:Java Stream - Compile time Error - Type mismatch: cannot convert from Map<Object,Object> to Map<Integer,List<String>>Java Stream - 编译时错误 - 类型不匹配:无法从 Map<Object,Object> 转换为 Map<Integer,List<String>>
【发布时间】: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


【解决方案1】:

您需要稍作更改,因为 split 返回 String []

np -> Arrays.asList(np.getAppsReceived().split(","))

【讨论】:

  • 这就是我使用 Arrays.asList 将其转换为列表的原因
  • @KaranVerma 很有趣,我采用了与您相同的代码,它只编译文件。 NumberUtils 返回什么?我假设一个整数?
  • 是的,它返回整数。
  • 我猜,它的 commons.apache NumberUtils.toInt,旨在通过默默地将 null 和空字符串转换为零来使错误代码变得更糟……
猜你喜欢
  • 1970-01-01
  • 2016-04-08
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
相关资源
最近更新 更多