简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM