遍历Map练习

65 阅读1分钟
public class test {
    public static void main(String[] args) {
        List<StudentScore> studentScoreList= Arrays.asList(
                new StudentScore("张三","语文",70),
                new StudentScore("张三","数学",70),
                new StudentScore("张三","英语",80),
                new StudentScore("李四","语文",80),
                new StudentScore("李四","数学",90),
                new StudentScore("李四","英语",50),
                new StudentScore("王五","语文",50),
                new StudentScore("王五","数学",60),
                new StudentScore("王五","英语",70)
        );
        HashMap<String, Integer> map = new HashMap<>();
        studentScoreList.forEach(studentScore -> {
            if (map.containsKey(studentScore.getStuName())){
                map.put(studentScore.getStuName(),map.get(studentScore.getStuName())+studentScore.getScore());
            }else {
                map.put(studentScore.getStuName(),studentScore.getScore());
            }
        });
        System.out.println(map);

        /**使用map的merge方法*/
        HashMap<String, Integer> map2 = new HashMap<>();
        studentScoreList.forEach(studentScore -> map2.merge(
                studentScore.getStuName(),
                studentScore.getScore(),
                (oldValue,newValue)->oldValue+newValue)
        );
        System.out.println(map2);
    }
}