枚举流Collectors.toMap问题

问题描述

我正在尝试将所有现有标头从请求复制到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)

解决方法

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

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

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

,

您的代码无法编译的原因是它的 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 值的映射。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...