使用Java 8流来转换具有空值的Map

Web*_*ser 10 java java-stream

我处理一个Map<String,String>具有null中键和/或值项:

Map<String, String> headers = new HashMap<>();
headers.put("SomE", "GreETing");
headers.put("HELLO", null);
headers.put(null, "WOrLd");

headers.keySet().stream().forEach(k -> System.out.println(k + " => " + copy.get(k)));
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

SomE => GreETing
HELLO => null
null => WOrLd
Run Code Online (Sandbox Code Playgroud)

我需要转换地图,所以所有非空值都转换为小写,如下所示:

some => greeting
hello => null
null => world
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用Java 8流API,但以下代码抛出NullPointerException:

Map<String,String> copy
    = headers.entrySet()
             .stream()
             .collect(
                 Collectors.toMap(
                     it -> it.getKey() != null ? it.getKey().toLowerCase() : null,
                     it -> it.getValue() != null ? it.getValue().toLowerCase() : null));

copy.keySet().stream().forEach(k -> System.out.println(k + " => " + copy.get(k)));
Run Code Online (Sandbox Code Playgroud)

如果我注释掉最后两个映射条目,程序就会执行,因此Collectors.toMap当键或值为空时,必须存在一个问题.如何使用流API解决此问题?

dka*_*zel 13

问题是toMap()调用构建的底层Map实现的merge()函数,该函数不允许值为null

来自javadoc Map#merge(强调我的)

如果指定的键尚未与值关联或与null关联,则将其与给定的非空值关联.否则,将相关值替换为给定重映射函数的结果,或者如果结果为null则删除.

所以使用Collectors.toMap()不起作用.

您可以在没有流的情况下做到这一点:

Map<String,String> copy = new HashMap<>();

for(Entry<String, String> entry : headers.entrySet()){
    copy.put(entry.getKey() !=null ? entry.getKey().toLowerCase() : null, 
             entry.getValue() !=null ? entry.getValue().toLowerCase() : null
            );
}
Run Code Online (Sandbox Code Playgroud)


use*_*739 10

使用收集:

final Function<String, String> fn= str -> str == null ? null : str.toLowerCase();
Map<String, String> copy = headers.entrySet().stream()
   .collect(HashMap::new,
            (m, e) -> m.put(fn.apply(e.getKey()), fn.apply(e.getValue())), 
            Map::putAll);
Run Code Online (Sandbox Code Playgroud)

或者使用AbacusUtil

Map<String, String> copy = Stream.of(headers)
   .collect(HashMap::new, 
     (m, e) -> m.put(N.toLowerCase(e.getKey()), N.toLowerCase(e.getValue())));
Run Code Online (Sandbox Code Playgroud)

2月4日更新,或者:

Map<String, String> copy = EntryStream.of(headers)
   .toMap(entry -> N.toLowerCase(entry.getKey()), entry -> N.toLowerCase(entry.getValue()));
Run Code Online (Sandbox Code Playgroud)