java - 如何将值存储在哈希图中>
问题描述
我有以下数组
我正在尝试将数组信息保存在哈希图中。
String[][] students = {{"Bobby", 87}, {"Charles", 100}, {"Eric", 64},
{"Charles", 22}};
Map<String, List<Integer>> map = new HashMap<>();
List<Integer> score1 = new ArrayList<>();
for(int i=0; i<students.length; i++) {
score1.add(students[i][1]);
map.put(students[i][0], score1);
}
但我想将信息存储在地图键值对中。
预期输出:
"Bobby" -> 87
"Charles" -> 100,22
"Eric" -> 64
实际输出:
{Charles=[87, 100, 64, 22], Eric=[87, 100, 64, 22], Bobby=[87, 100, 64, 22]}
我怎样才能做到这一点?
解决方案
使用 java-8,您可以在一行中使用以下所有内容:
Map<String, List<Integer>> collect1 =
Arrays.stream(students).collect(Collectors.groupingBy(arr -> arr[0],
Collectors.mapping(arr -> Integer.parseInt(arr[1]), Collectors.toList())));
在这里,我们按学生姓名的第 0 个索引分组,第一个索引将保存学生的分数。
推荐阅读
- python - 使用 Python/C# 进行动态 Google 搜索
- python - 如何在 pandas 数据帧上进行迭代以在每次迭代中获取多行
- rust - Rust,在迭代中需要一个可变的 Self 引用
- python - Python从字典创建类实例
- c# - System.InvalidOperationException: '预期的浏览器二进制位置,但在 C# 中使用 Firefox Selenium 时无法在默认位置找到二进制错误
- java - 在 Android Studio 中导入库 DirectoryChooser
- python - 理解 [0] 在以下 Python pandas 代码中的重要性
- python - 如何在 Python 中为两列中的每个唯一值计算加权平均值?
- html - 为什么 DataTables 在渲染函数中剥离自定义属性?
- excel - 在列中查找多次出现的值。然后删除整行