Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
led Avatar asked Dec 16 '22 00:12

led


1 Answers

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)
like image 182
Louis Wasserman Avatar answered Jan 14 '23 12:01

Louis Wasserman