led led - 10 months ago 67
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()
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>>:

  m -> DateTimeFormatter.ofPattern("MMM").format(m)),
  (v1, v2) -> // whatever,