ERROR: Type mismatch: cannot convert from Map<Object,List<Object>> to Map<String,List<>>

ERROR: Type mismatch: cannot convert from Map<Object,List<Object>> to Map<String,List<>>

我有一个要使用属性分组的列表。我不确定为什么会收到错误

Type mismatch: cannot convert from Map<Object,List> to Map<String,List<MyClass.Leader>>

调用领导者时class。我正在使用 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;
    }
}

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

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 块,以便正确关闭流。