[英]Initialize Map<String, Object> instance from Map entries
Say I have some map entries like so: 说我有一些像这样的地图条目:
var a = Map.entry("a", new Object());
var b = Map.entry("b", new Object());
var c = Map.entry("c", new Object());
var m = Map.of(a,b,c); // error here
I get this error: 我收到此错误:
Cannot resolve method 'of(java.util.Map.Entry, java.util.Map.Entry, java.util.Map.Entry)'
无法解析方法'(java.util.Map.Entry,java.util.Map.Entry,java.util.Map.Entry)'
I just want to make a new Map from entries in a map, how can I do this? 我只是想从地图中的条目创建一个新的地图,我该怎么做? Not the question is specifically about how to init a Map given Map.Entry instances.
问题不在于如何在给定Map.Entry实例的情况下初始化Map。
Replace 更换
Map.of(a,b,c);
with 同
Map.ofEntries(a,b,c);
If you want to still use Map.of()
then you shall paste keys and values explicitly. 如果你仍想使用
Map.of()
那么你应该明确地粘贴键和值。
Map.Entry()
returns an immutableMap.Entry
containing the given key and value.Map.Entry()
返回包含给定键和值的不可变Map.Entry
。 These entries are suitable for populating Map instances using theMap.ofEntries()
method.这些条目适合使用
Map.ofEntries()
方法填充Map实例。
When to use Map.of()
and when to use Map.ofEntries()
何时使用
Map.of()
以及何时使用Map.ofEntries()
From jdk-9 you can use Map.of()
to create Map
with key value pairs 从jdk-9开始,您可以使用
Map.of()
创建具有键值对的Map
Map<String, Object> map = Map.of("a", new Object(), "b", new Object(), "c", new Object());
And also by using SimpleEntry
并且还使用
SimpleEntry
Map<String, Object> map = Map.ofEntries(
new AbstractMap.SimpleEntry<>("a", new Object()),
new AbstractMap.SimpleEntry<>("b", new Object()),
new AbstractMap.SimpleEntry<>("c", new Object()));
Or by using Map.ofEntries
OP suggestion 或者使用
Map.ofEntries
OP建议
The simple answer is: 简单的答案是:
var a = Map.entry("a", new Object());
var b = Map.entry("b", new Object());
var c = Map.entry("c", new Object());
var m = Map.ofEntries(a,b,c); // ! use Map.ofEntries not Map.of
And the type of Map.entry(key,val)
is Map.Entry<K,V>
, in case you were wondering. Map.entry(key,val)
的类型是Map.Entry<K,V>
,以防你想知道。
Use this 用这个
var m = Map.ofEntries(a, b, c);
instead of 代替
var m = Map.of(a,b,c);
To create a map from entries Use either: 从条目创建地图使用以下任一方法:
var a = Map.entry("a", new Object());
var b = Map.entry("b", new Object());
var c = Map.entry("c", new Object());
var m = Map.ofEntries(a,b,c);
or: 要么:
var m = Map.ofEntries(
entry("a", new Object()),
entry("b", new Object()),
entry("c", new Object()));
You can also create the map without explicitly creating the entries: 您也可以在不显式创建条目的情况下创建地图:
var m = Map.of("a", new Object(),
"b", new Object(),
"c", new Object());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.