2021年3月6日星期六

Instantiate a Map from a set of key objects, in Java

Given a Set of objects that I want to use as keys, how can I easily get a Map instance leaving the values as null?

The purpose is to pre-populate the map with keys before determining the values to be stored.

Of course, I could create an empty map, then loop the set of would-be key objects, while doing a put on each, along with null as the value.

Set< Month > months = EnumSet.of( Month.MARCH , Month.MAY , Month.JUNE ) ;   Map< Month , String > map = new EnumMap<>( Month.class ) ;  for( Month month : months )   {      map.put( month , null ) ;  }  

I just wonder if there is a nifty trick to do this with less code. Something like the opposite of Map#keySet.

https://stackoverflow.com/questions/66510736/instantiate-a-map-from-a-set-of-key-objects-in-java March 07, 2021 at 05:21AM

没有评论:

发表评论