最后,我们再来看看JDK1.8中集合类新增的一些操作(之前没有提及的)首先来看看compute方法:

    1. public static void main(String[] args) {
    2. Map<Integer, String> map = new HashMap<>();
    3. map.put(1, "A");
    4. map.put(2, "B");
    5. map.compute(1, (k, v) -> { //compute会将指定Key的值进行重新计算,若Key不存在,v会返回null
    6. return v+"M"; //这里返回原来的value+M
    7. });
    8. map.computeIfPresent(1, (k, v) -> { //当Key存在时存在则计算并赋予新的值
    9. return v+"M"; //这里返回原来的value+M
    10. });
    11. System.out.println(map);
    12. }

    也可以使用computeIfAbsent,当不存在Key时,计算并将键值对放入Map

    1. public static void main(String[] args) {
    2. Map<Integer, String> map = new HashMap<>();
    3. map.put(1, "A");
    4. map.put(2, "B");
    5. map.computeIfAbsent(0, (k) -> { //若不存在则计算并插入新的值
    6. return "M"; //这里返回M
    7. });
    8. System.out.println(map);
    9. }

    merge方法用于处理数据:

    1. public static void main(String[] args) {
    2. List<Student> students = Arrays.asList(
    3. new Student("yoni", "English", 80),
    4. new Student("yoni", "Chiness", 98),
    5. new Student("yoni", "Math", 95),
    6. new Student("taohai.wang", "English", 50),
    7. new Student("taohai.wang", "Chiness", 72),
    8. new Student("taohai.wang", "Math", 41),
    9. new Student("Seely", "English", 88),
    10. new Student("Seely", "Chiness", 89),
    11. new Student("Seely", "Math", 92)
    12. );
    13. Map<String, Integer> scoreMap = new HashMap<>();
    14. students.forEach(student -> scoreMap.merge(student.getName(), student.getScore(), Integer::sum));
    15. scoreMap.forEach((k, v) -> System.out.println("key:" + k + "总分" + "value:" + v));
    16. }
    17. static class Student {
    18. private final String name;
    19. private final String type;
    20. private final int score;
    21. public Student(String name, String type, int score) {
    22. this.name = name;
    23. this.type = type;
    24. this.score = score;
    25. }
    26. public String getName() {
    27. return name;
    28. }
    29. public int getScore() {
    30. return score;
    31. }
    32. public String getType() {
    33. return type;
    34. }
    35. }