遍历2D数组并将值映射

时间:2020-03-22 11:30:02

标签: java

我想遍历此2d数组并将值作为键和字符串列表放入“字符串映射”中 基本上我有这个,但是在键已经存在的情况下,我无法修改值列表以添加另一个值

  static float bestAverageStudent(String[][] students) {
        Map<String, List<String>> grades = new HashMap<>();
        for (int row = 0; row < students.length; row++) {
            for (int col = 0; col < students[row].length; col++) {
                if (grades.get(students[row][0]) == null) {
                    grades.put(students[row][0], Arrays.asList(students[col][1]));
                } else {
                    List<String> strings1 = grades.get(students[row][0]);
                    strings1.add( students[col][1]);               //It fails when i try to add to the list
                    grades.put(students[row][0], new ArrayList<>(strings1));
                }
            }
        }
        System.out.println(grades);
        return 0;

这是数组

 public static String students[][] = new
            String[][]{{"jerry", "65"},
            {"bob", "91"},
            {"jerry", "23"},
            {"Eric", "83"}};

我想将此记录保存在一张地图中,其中的值是一个学生的成绩列表

谢谢

2 个答案:

答案 0 :(得分:3)

第一个问题来自Java List.add() UnsupportedOperationException ,它为您提供返回固定大小的列表,您需要将其包装在ArrayList中,例如new ArrayList<>(Arrays.asList(...))

但是,您也不需要重复迭代数组,就可以知道数组的结构,只需迭代第一个数组并访问2个值即可:

Map<String, List<String>> grades = new HashMap<>();
for (int row = 0; row < students.length; row++) {
    String name = students[row][0];
    String grade = students[row][1];
    if (!grades.containsKey(name)) {
        grades.put(name, new ArrayList<>(Arrays.asList(grade)));
    } else {
        List<String> strings1 = grades.get(name);
        strings1.add(grade);
        grades.put(name, new ArrayList<>(strings1));
    }
}

使用Streams

Map<String, List<String>> grades = Arrays.stream(students)
                .collect(groupingBy(values -> values[0], mapping(values -> values[1], toList())));

答案 1 :(得分:2)

由于Arrays.asList(...)返回AbstractList的实现,从而导致了问题。

尝试此更新的代码:

Map<String, List<String>> grades = new HashMap<>();
for (int row = 0; row < students.length; row++) {
    for (int col = 0; col < students[row].length; col++) {
        if (!grades.containsKey(students[row][0])) {
            List<String> list = new ArrayList<>();
            list.add(students[col][1]);
            grades.put(students[row][0], list);
        } else {
            List<String> strings1 = grades.get(students[row][0]);
            strings1.add(students[col][1]);//It fails when i try to add to the list
            grades.put(students[row][0], new ArrayList<>(strings1));
        }
    }
}
System.out.println(grades);
return 0;