gpt4 book ai didi

java - 在 Java 8 中使用收集器的简单示例

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:56 24 4
gpt4 key购买 nike

假设我有一个这样的文件:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com