假设我有一个这样的文件:
1, Apple
1, Pear
1, Orange
2, Apple
3, Melon
3, Orange
我想将其解析为一个列表,其中每个条目都是一个映射,或者我猜它可能是我自己的对象,但我认为最好是映射,因为它是一个键。值(value)。
我在尝试:
private List<Map<String, String>> readRecords(String path) {
return Files.lines(Paths.get(path))
.map(line -> Arrays.asList(line.split(SEPARATOR)))
.map(snippets -> new HashMap<Integer, String>().put(Integer.parseInt(snippets.get(0)), snippets.get(1)))
.collect(Collectors.toList());
}
但这给了我一个关于无法在 List<String>
之间转换的错误和 List<Map<String, String>>
或者也许有更好的方法来做到这一点?
最佳答案
除了返回类型不正确(List<Map<Integer, String>>
)之外,put
方法将为您提供之前映射的值(如果有)。
所以
.map(snippets -> new HashMap<Integer, String>().put(Integer.parseInt(snippets.get(0)), snippets.get(1)))
实际上是一个映射List<String> -> String
而不是 List<String> -> Map<Integer, String>
.
如果您想坚持使用官方 API,我会返回一个 List<SimpleEntry<Integer, String>>
相反,因为每一行代表一个键值对并更改 map
调用:
.map(snippets -> new SimpleEntry<>(Integer.parseInt(snippets.get(0)), snippets.get(1)))
... 或将全部内容收集到 Map<Integer, List<String>>
中(查看 groupingBy
收集器)。
关于java - 在 Java 8 中使用收集器的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809108/