Java 8 lambda specifies the map type and makes it immutable
•
Java
I have the following code, generated using Lambdas for several months
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 wonder if I can use Lambdas to do all this at once?
return EnumSet.allOf(Month.class).stream() .collect(Collectors.collectingAndThen(Collectors.toMap( Month::getValue,m -> DateTimeFormatter.ofPattern("MMM").format(m) ),Collections::unmodifiableMap));
It doesn't work Where do I specify that I want to use LinkedHashMap?
Solution
You need to use the collectors toMap overload that accepts a Supplier
Collectors.toMap(Month::getValue,m -> DateTimeFormatter.ofPattern("MMM").format(m)),(v1,v2) -> // whatever,LinkedHashMap::new)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码