不要再用if(xxx != null)或者try catch NullPointerException了,Optional可以帮你解决
public static void testIfPresent() { Map<String, Map<String, String>> map = new HashMap<>(); String firstKey = "hjz", secondKey = "lxk"; Map<String, String> childMap = new HashMap<>(); childMap.put("lxk", "sbj"); map.put("hjz", childMap); ifPresent(map, firstKey, secondKey, System.out::print); } public static void ifPresent(Map<String, Map<String, String>> map, String firstKey, String secondKey, Consumer<String> consumer) { ofNullable(map.get(firstKey)).ifPresent(childMap -> ofNullable(childMap.get(secondKey)).ifPresent(consumer)); }
本文来自博客园,作者:hjzqyx,转载请注明原文链接:https://www.cnblogs.com/hujunzheng/p/8058474.html