枚举流Collectors.toMap问题

时间:2020-09-09 23:50:17

标签: java-stream collectors

我正在尝试将所有现有标头从请求复制到Spring HttpHeaders对象,以在RestTemplate中使用。可以很容易地在枚举循环中完成,但是在使用流时会出现此错误

HttpHeaders headers = new HttpHeaders();
Enumeration<String> existingHeaders = request.getHeaderNames();

headers.putAll(
 Collections.list(existingHeaders)
.stream()
.collect(
Collectors.toMap(Function.identity(),HttpServletRequest::getHeader))

);

我为流声明了变量Enumeration<String>,以不将元素视为对象,但在collect()上仍遇到此编译错误

    The method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) 
    in the type Collectors is not applicable for the arguments
    (Function<Object,Object>, HttpServletRequest::getHeader)

2 个答案:

答案 0 :(得分:0)

要从 HttpHeaders 获取 HttpServletRequest,您可以使用 spring-web 中的 ServletServerHttpRequest 类。由于 HttpHeaders 类也在 spring-web 中,因此您应该已经在类路径中提供了此类。

private static HttpHeaders getHttpHeaders(HttpServletRequest request) {
  return new ServletServerHttpRequest(request).getHeaders();
}

这个答案没有解决您收到错误的原因,尽管它确实解决了您试图解决的潜在问题:从现有的 HttpHeaders 获取 HttpServletRequest。< /p>

答案 1 :(得分:0)

您的代码无法编译的原因是它的 Collectors.toMap(...) 调用产生了一个 Map<String, String>,但 headers.putAll(...) 需要一个 Map<String, List<String>>。这可以通过更改 Collectors.toMap(...) 调用以生成兼容的地图来解决:

HttpHeaders headers = new HttpHeaders();
Enumeration<String> existingHeaders = request.getHeaderNames();

headers.putAll(Collections.list(existingHeaders)
        .stream()
        .collect(Collectors.toMap(Function.identity(), 
                name -> Collections.list(request.getHeaders(name)))));

由于同一个 HTTP 标头可以有多个值,HttpHeaders 实现了 Map<String,List<String>> 而不是 Map<String,String>。因此,putAll(map) 需要具有 List<String> 值的映射,而不是具有 String 值的映射。