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

  输出结果如下

jdk8Map操作,compute,computeIfPresent,merge方法

 

上一篇:jmeter+jenkins邮件模板


下一篇:解决zun docker vif_type(binding_failed) is not supported.A binding script for this type can‘t be found