Last active
August 29, 2015 14:21
-
-
Save henri-tremblay/ecfda175a82abbc26040 to your computer and use it in GitHub Desktop.
What is the real functional way?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Map<String, List<String>> mapHeaders(Header[] headers) { | |
Map<String, List<String>> headerMap = new HashMap<>(); | |
Arrays.stream(headers) | |
.forEach(h -> { | |
List<String> values = headerMap.get(h.getName()); | |
if(values == null) { | |
values = new ArrayList<String>(); | |
headerMap.put(h.getName(), values); | |
} | |
values.add(h.getValue()); | |
}); | |
return headerMap; | |
} | |
// slightly improved version. But I still have the forEach | |
private Map<String, List<String>> mapHeaders(Header[] headers) { | |
Map<String, List<String>> headerMap = new HashMap<>(); | |
Arrays.stream(headers) | |
.forEach(h -> { | |
headerMap.computeIfAbsent(h.getName(), k -> new ArrayList<>()).add(h.getValue()); | |
}); | |
return headerMap; | |
} | |
// The answer! | |
private Map<String, List<String>> mapHeaders(Header[] headers) { | |
Map<String, List<String>> headerMap = Arrays.stream(headers) | |
.collect(Collectors.groupingBy(Header::getName, Collectors.mapping(Header::getValue, Collectors.toList()))); | |
return headerMap; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With static imports and inlining:
Could be more readable.