Issue
I'm trying to copy all existing headers from an HttpServletRequest
to a Spring HttpHeaders
object to use with RestTemplate
. This can be done easily in a loop on enumeration, but I'm getting this error while using streams:
HttpHeaders headers = new HttpHeaders();
Enumeration<String> existingHeaders = request.getHeaderNames();
headers.putAll(
Collections.list(existingHeaders)
.stream()
.collect(
Collectors.toMap(Function.identity(),HttpServletRequest::getHeader))
);
I declared the variable Enumeration<String>
for the stream to not consider elements as Object but I'm still getting this compilation error at 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)
Solution
The reason your code does not compile is that its Collectors.toMap(...)
call is producing a Map<String, String>
, but headers.putAll(...)
requires a Map<String, List<String>>
. This can be fixed by changing the Collectors.toMap(...)
call to produce a compatible map:
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)))));
Since the same HTTP header can have multiple values, HttpHeaders
implements Map<String,List<String>>
rather than Map<String,String>
. Therefore, putAll(map)
requires a map with List<String>
values, not one with String
values.
Answered By - M. Justin