jdk8Map操作,compute,computeIfPresent,merge方法

比如,统计出现的次数

List<String> animals = Arrays.asList("dog", "cat", "cat", "dog", "fish", "dog");

  方法一:

Map<String, Integer> map = new HashMap<>();
        for (String animal : animals) {
            map.compute(animal, (k, v) -> v == null ? 1 : ++v);
        }

  方法二:

Map<String, Integer> map1 = new HashMap<>();
        for (String animal : animals) {
            map1.putIfAbsent(animal, 0);
            map1.computeIfPresent(animal, (k, v) -> ++v);
        }

  方法三:

Map<String, Integer> map2 = new HashMap<>();
        for (String animal : animals) {
            map2.putIfAbsent(animal, 0);
            map2.merge(animal, map2.get(animal), (k, v) -> ++v);
        }

  输出结果如下

 

posted @ 2021-09-15 16:29  木马不是马  阅读(173)  评论(0编辑  收藏  举报