在 Java 中从一组关键对象实例化一个 Map
Instantiate a Map from a set of key objects, in Java
给定 Set
个我想用作键的对象,我怎样才能轻松获得一个 Map
实例并将值保留为 null?
目的是在确定要存储的值之前用键预填充地图。
当然,我可以创建一个空映射,然后循环一组可能的关键对象,同时对每个对象执行 put
,并将 null
作为值。
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 ) ;
}
我只是想知道是否有一个巧妙的技巧可以用更少的代码来做到这一点。类似于 Map#keySet
.
的反义词
set.stream().collect(Collectors.toMap(k -> k, k -> null));
Collectors.toMap()
和像 Map.of()
这样的静态工厂方法在内部使用 Map.merge
如果键或值为 null 将抛出 NPE。
看到这个post:java-8-nullpointerexception-in-collectors-tomap. And see this issue page on the OpenJDK project: JDK-8148463 Collectors.toMap fails on null values
您可以通过使用 Stream.collect
和三个参数签名作为缩减来解决。
collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
类似于:
Set< Month > months = EnumSet.of( Month.MARCH , Month.MAY , Month.JUNE ) ;
Map< Month , String > myMap =
months.stream()
.collect(
HashMap::new ,
( map , val )-> map.put( val , null ) ,
HashMap::putAll
);
System.out.println(myMap);
看到code run live at IdeOne.com。
但我不确定这是否比您使用经典 for 循环的方法更具可读性或更优雅
给定 Set
个我想用作键的对象,我怎样才能轻松获得一个 Map
实例并将值保留为 null?
目的是在确定要存储的值之前用键预填充地图。
当然,我可以创建一个空映射,然后循环一组可能的关键对象,同时对每个对象执行 put
,并将 null
作为值。
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 ) ;
}
我只是想知道是否有一个巧妙的技巧可以用更少的代码来做到这一点。类似于 Map#keySet
.
set.stream().collect(Collectors.toMap(k -> k, k -> null));
Collectors.toMap()
和像 Map.of()
这样的静态工厂方法在内部使用 Map.merge
如果键或值为 null 将抛出 NPE。
看到这个post:java-8-nullpointerexception-in-collectors-tomap. And see this issue page on the OpenJDK project: JDK-8148463 Collectors.toMap fails on null values
您可以通过使用 Stream.collect
和三个参数签名作为缩减来解决。
collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
类似于:
Set< Month > months = EnumSet.of( Month.MARCH , Month.MAY , Month.JUNE ) ;
Map< Month , String > myMap =
months.stream()
.collect(
HashMap::new ,
( map , val )-> map.put( val , null ) ,
HashMap::putAll
);
System.out.println(myMap);
看到code run live at IdeOne.com。
但我不确定这是否比您使用经典 for 循环的方法更具可读性或更优雅