java将map的key转为大写

发布时间 2023-09-20 09:36:06作者: ContinueW

普通的stream流,toMap方法会调用merge方法,该方法如果value传值为null的时候,会报空指针异常,因此直接使用collect()方法进行规约操作

public static void main(String[] args) {
Map<String, String> testMap = new HashMap<>();
testMap.put("apple", null);
testMap.put("banana", null);
testMap.put("orange", "3");

testMap = testMap.entrySet()
.stream()
.collect(HashMap::new, (map, item) -> map.put(item.getKey().toUpperCase(), item.getValue()),
HashMap::putAll);

System.out.println(testMap);
}