如何使用<字符串,列表>将值存储在哈希图中<Integer>



我有以下数组

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

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个索引进行分组,第1个索引将包含学生的分数。

您需要区分现有数组和新数组:

List<Integer> currScore = map.get(students[i][0])
if (currScore != null) {
currScore.add(students[i][1]);
} else {
List<Integer> newScore = new ArrayList<>();
newScore.add(students[i][1]);
map.put(students[i][0], newScore);
}

还将变量名称更改为有意义的名称

String[][] students = { { "Bobby", "87" }, { "Charles", "100" }, { "Eric", "64" }, { "Charles", "22" } };
Map<String, List<Integer>> map = new HashMap<>();
Stream.of(students).forEach(student -> map.computeIfAbsent(student[0], s -> new ArrayList<>()).add(Integer.parseInt(student[1])));

您可以在这里检查为什么您的原始代码甚至不会编译:https://ideone.com/AWgBWl

在对你的代码进行了几次修复后,这是一种正确的方法(遵循你的逻辑(:

// values should be like this {"Bobby", "87"} because you declared it as
// an array of strings (String[][]), this {"Bobby", 87} is a String and an int
String[][] students = {{"Bobby", "87"}, {"Charles", "100"}, {"Eric", "64"}, {"Charles", "22"}};
// the inner list must be of Strings because of the previous comment
Map<String, List<String>> map = new HashMap<>();
// list of strings because of the previous comment
List<String> score1;
for(int i = 0; i < students.length; i++) {
score1 = map.get(students[i][0]);     // check if there is a previously added list
if (score1 == null) {
score1 = new ArrayList<>();      // create a new list if there is not one previously added for that name
map.put(students[i][0], score1);
}
map.get(students[i][0]).add(students[i][1]); // add a new value to the list inside the map
}
System.out.println(map.toString());
// {Charles=[100, 22], Eric=[64], Bobby=[87]}

此处演示:https://ideone.com/SJpTHs

由于初始化了循环外的列表并将其用于所有附加,因此hashmap中的所有条目都引用了相同的实例。对于学生中的每个条目,您需要检查是否已经有该学生的列表。如果是,则检索该特定列表并将其追加。如果不是,则创建一个新列表,然后追加。for循环中的代码如下所示:

String name = students[i][0];
List<Integer> scores = map.get(name);
if (scores == null) {
scores = new ArrayList<>();
}
scores.add(students[i][1]);
map.put(name, scores);

最新更新