【问题标题】:ERROR: Type mismatch: cannot convert from Map<Object,List<Object>> to Map<String,List<>>错误:类型不匹配:无法从 Map<Object,List<Object>> 转换为 Map<String,List<>>
【发布时间】:2021-04-15 05:20:58
【问题描述】:

我有一个使用属性分组的列表。我不知道为什么会出错

类型不匹配:无法从 Map 转换为 Map>

调用领导者类时。我正在使用 Java 8。

Map<String, List<Leader>> reports = vals.stream()
    .collect(
        Collectors.mapping(val -> val.split("\\|"),
            Collectors.mapping(leaderArgs -> new Reports(leaderArgs[0], leaderArgs[1], leaderArgs[2], leaderArgs[3]),
                Collectors.groupingBy(leader -> leader.country))));

```java
public class Leader {
    String name;
    String country;
    String age;
    String sex;

    Leader(String name, String country, String age, String sex) {
        this.name = name;
        this.country = country;
        this.age = age;
        this.sex = sex;
    }
}

【问题讨论】:

  • 这无法编译 - 您正在为您的班级使用 4 个名称 - Leaders、Reports、Leader、Report。将所有这些更改为 Leader 就可以了。
  • @greg-449 仍然出现同样的错误。
  • 您使用的是什么版本的 Eclipse?更正后的代码在当前的 Eclipse 2021-03 上很好
  • @greg-449 我正在使用 Eclipse Photon v4.8.0
  • 那么 Eclipse Photon 现在已经过时了 11 个版本,很可能已经修复了较新版本中流的类型推断代码,因为这是一个非常棘手的领域。

标签: java eclipse maven mismatch


【解决方案1】:

以下代码与您的代码执行相同的操作,但将收集拆分为多个地图步骤,这可能更适合您:

Pattern splitPattern = Pattern.compile("\\|");

Map<String, List<Leader>> result =
      vals.stream()
          .map(splitPattern::split)
          .map(leaderArgs -> new Leader(leaderArgs[0], leaderArgs[1], leaderArgs[2], leaderArgs[3]))
          .collect(Collectors.groupingBy(leader -> leader.country));

我也使用了Pattern,它比重复调用 String.split 快一点。

简单的 XML 输出可能是:

result.entrySet()
    .forEach(entry -> {
        System.out.println("<LeaderList country=\"" + entry.getKey() + "\">");

        entry.getValue()
             .forEach(leader -> System.out.println("<Leader name=\"" + leader.name + "\" age=\"" + leader.age + "\" sex=\"" + leader.sex + "\">"));

        System.out.println("</LeaderList>");
    });

收集代码假设输入 vals 是一个字符串流,每行一个条目。例如读取文件:

Path path = ... file path

try (Stream<String> vals = Files.lines(path))
  {
    ... the collect code
  }
catch (final IOException ex)
 {
   // TODO error handling
 }

注意:请务必使用带有 Files.lines 的 try-with-resources 块,以便正确关闭流。

【讨论】:

  • 抱歉,错过了从我的测试代码复制到 stream() 的电话。查看更新的答案。
  • 这应该不是必需的,但您可以尝试.map((String line) -&gt; splitPattern.split(line)) 分割线或尝试原来的.map(val -&gt; val.split("\\|"))。还要确保流的所有其余部分都是正确的,因为流的错误消息可能会产生误导。
  • 上面的代码只是生成一个地图,它不会打印任何东西,因为这不是你在这个问题中所问的。在我的测试中,地图是正确的。听起来您可能没有在打印代码中正确处理地图。
  • 我添加了一些示例 XML 输出代码
  • 在我的测试中,这完全符合您的要求。提出一个新问题,将您的所有代码显示为minimal reproducible example
猜你喜欢
  • 2016-04-08
  • 2017-04-17
  • 1970-01-01
  • 2015-12-18
  • 2019-09-29
  • 2018-09-22
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
相关资源
最近更新 更多