如何使用lambda初始化地图? [英] How to initialize a map using a lambda?
问题描述
我要在单个语句(可能包含多个嵌套语句)中声明完全填充的地图字段,如下所示:
I want to declare a fully populated map field in a single statement, (which may contain several nested statements,) like this:
private static final Map<Integer,Boolean> map =
something-returning-an-unmodifiable-fully-populated-HashMap;
匿名初始化器不会这样做,因为调用函数返回一个新的填充映射将不会:它们需要两个顶级语句:一个用于变量声明,一个用于方法或初始化器。
Anonymous initializers won't do, for the same reason that invoking a function which returns a new populated map won't do: they require two top-level statements: one for the variable declaration, and one for the method or initializer.
双花括号( {{
和}}
)idiom将工作,但它创建一个新的类,扩展 HashMap& >
,我不喜欢这个开销。
The double curly bracket ({{
and }}
) idiom will work, but it creates a whole new class which extends HashMap<>
, and I do not like the overhead represented by this.
Java 8的lambda可能提供一个更好的方法来完成这个?
Do the lambdas of Java 8 perhaps offer a better way of accomplishing this?
推荐答案
以下是如何使用lambda实现字段初始值设定。
Here is how to implement a field initializer using a lambda.
private static final Map<Integer,Boolean> map =
((Supplier<Map<Integer,Boolean>>)(() -> {
Map<Integer,Boolean> map = new HashMap();
map.put( 1, false );
map.put( 2, true );
return Collections.unmodifiableMap( map );
})).get();
这篇关于如何使用lambda初始化地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!