繁体   English   中英

如何在hashmap中存储值 <String, List<Integer> &gt;

[英]How can I store values in a hashmap with <String, List<Integer>>

我有以下数组

我试图将数组信息保存在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]}

我怎样才能做到这一点?

使用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);
 }

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

您可以在此处查看原始代码甚至无法编译的原因: 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

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])));

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

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM