>,java,hashmap"/>

首页 > 解决方案 > 如何将值存储在哈希图中>

问题描述

我有以下数组

我正在尝试将数组信息保存在哈希图中。

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]}

我怎样才能做到这一点?

标签: javahashmap

解决方案


使用 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 个索引分组,第一个索引将保存学生的分数。


推荐阅读