I have the following code, which produces months using lambdas.
Map<Integer, String> tempMap = new LinkedHashMap<>();
EnumSet.allOf(Month.class).forEach(m -> {
String formattedMonth = DateTimeFormatter.ofPattern("MMM").format(m);
tempMap.put(m.getValue(), formattedMonth);
});
MONTHS_MAP = Collections.unmodifiableMap(tempMap);
I was wondering if this can be improved to perform all of these at one shot using lambdas?
return EnumSet.allOf(Month.class).stream()
.collect(Collectors.collectingAndThen(Collectors.toMap(
Month::getValue,
m -> DateTimeFormatter.ofPattern("MMM").format(m)
), Collections::unmodifiableMap));
This doesn't work. Where do I specify that I would like to use a LinkedHashMap?
You need to use the Collectors.toMap
overload that accepts a Supplier<Map<K, V>>
:
Collectors.toMap(Month::getValue,
m -> DateTimeFormatter.ofPattern("MMM").format(m)),
(v1, v2) -> // whatever,
LinkedHashMap::new)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With