Map的几个新API测试

140 阅读2分钟

刚开始参加工作的时候,去一些公司面试经常会让你手写一个编程题,统计某个字符串,各个字符出现的次数,然后我们就开始各种遍历巴拉巴拉写出一大堆,但是JDK1.8已经提供了两种成熟的方法来做这个事情,借此和大家温顾一下map的新API,在工作中也是经常用到的,如果你不晓得话,很有可能写了很多行还被同事说一下,review的时候也会暴露自己,不管咋说,掌握这个很有必要

1.测试map.getOrDefault

/** 测试map.getOrDefault,获取value为null的时候就给你一个默认值
 * 曾经看到有同学这样写的,没必要
 *
 * */
@Test
public void testMap4() {
  Map<String, Integer> map = new HashMap();
  map.put("java", 1);
  map.put("mysql", 2);
  Integer result = map.getOrDefault("java1", 6);
  System.out.println(result);
  Integer roy = map.get("roy");
  //Integer roy1 = map.getOrDefault("roy", null);
  System.out.println(roy);

//Integer roy1 = map.getOrDefault("roy", null);

有些小伙伴这样写,显得有些画蛇添足了,注意一下

2.测试map.computeIfAbsent

/**
 *
 * computeIfAbsent的方法,实际上都是一个计算,当你拿到的value是空的,自己new一个 ,等价于上一个
 * 取出的value的类型是List,同样是null的时候,可以给一个默认值,可以.add往value中添加元素
 * */
@Test
public void testomputeIfAbsent() {
  Map<String, List<String>> map = new HashMap();
  List<String> list = new ArrayList<>();
  list.add("roy");
  map.put("java", list);
  map.computeIfAbsent("java", key -> new ArrayList<>()).add("Spring");
  List<String> list1 = new ArrayList<>();
  list1.add("tony");
  map.computeIfAbsent("java1", key -> list1).add("mybatis");
  System.out.println(map);
}

3.测试map.compute

/**
 * 统计一个字符串各个字符出现的次数
 *
 */
@Test
public void testMapCompute() {
  Map<String, Integer> map = new HashMap();
  String param = "roy you are the best";
  String[] split = param.split("");
  Arrays.stream(split).forEach(charactor -> {
    map.compute(charactor, (k, v) -> {
      if (map.get(k) == null ){
        return 1;
      }else {
        return v + 1;
      }
    });
  });
  System.out.println(map);
}

4.测试countMap.merge

/**
 * merge的用法,等价于上一个 ,统计字符串的用法,功能和map.compute一样
 *
 * */
@Test
public void testMap3() {
  Map<String, Integer> countMap = new HashMap();
  /*countMap.merge("java", 1, Integer::sum);
  System.out.println(countMap);*/
  String str = "roy you are the best";
  for (int i = 0; i < str.length(); i++) {
    countMap.merge(str.substring(i, i + 1), 1, Integer::sum);
  }
  System.out.println(countMap);
}

学会了这4种Map高级一丢丢的API一定会让你的代码熠熠生辉