led led - 4 months ago 33
Java Question

Java 8 Lambda specify map type and make it unmodifiable

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?

Answer

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)
Comments