简体   繁体   English

Java 8 Lambda指定地图类型并使其不可修改

[英]Java 8 Lambda specify map type and make it unmodifiable

I have the following code, which produces months using lambdas. 我有以下代码,使用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? 我想知道是否可以使用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? 我在哪里指定我想使用LinkedHashMap?

You need to use the Collectors.toMap overload that accepts a Supplier<Map<K, V>> : 您需要使用接受Supplier<Map<K, V>>Collectors.toMap重载

Collectors.toMap(Month::getValue, 
  m -> DateTimeFormatter.ofPattern("MMM").format(m)),
  (v1, v2) -> // whatever,
  LinkedHashMap::new)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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