java Arrays.asList 也用于地图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40449848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Arrays.asList also for maps?
提问by PowerFlower
I have the below code:
我有以下代码:
Map<String, Map<Double, String>> map = new HashMap<>();
Map<Double,String> Amap = new HashMap<>();
map.put(getValuesTypes.FUT(), HERE);
Instead of creating a Map first and put it at "HERE", I'm looking for a function like I could use with a List
there Arrays.asList(...)
so that i can just enter at "Here" ?.asMap({1.0,"A"}, {2.0,"B"})
我没有先创建地图并将其放在“HERE”中,而是在寻找一个可以与List
there一起使用的函数,这样我就Arrays.asList(...)
可以输入"Here" ?.asMap({1.0,"A"}, {2.0,"B"})
采纳答案by nakano531
You can initialize HashMap
like this.
你可以这样初始化HashMap
。
new HashMap<Double, String>() {
{
put(1.0, "ValA");
put(2.0, "ValB");
}
};
回答by Olimpiu POP
Guava's ImmutableMap.of(..)can help in this direction:
Guava 的ImmutableMap.of(..)可以在这个方向上提供帮助:
ImmutableMap.of(1, "a");
in the JDK there is only Collections.singletonMap(..), but this provides you just a map with a sole pair.
在 JDK 中只有Collections.singletonMap(..),但这仅为您提供了一个带有唯一对的地图。
There was a discussionin guava projectto contain a Maps.asMap(Object... varArgs)
, bit it was stopped. So, ImmutableMap.of(...) is the way to go.
在番石榴项目中有一个包含一个的讨论,它被停止了。所以, ImmutableMap.of(...) 是要走的路。Maps.asMap(Object... varArgs)
EDIT since JDK 9
自 JDK 9 起编辑
In JDK 9 there were added new methods that do the same thing: Map.of(K,V)
在 JDK 9 中添加了执行相同操作的新方法: Map.of(K,V)
回答by Andrew Tobilko
There is no literal to initialize a map in that way. But you could use an anonymous class generating on the spot:
没有文字可以以这种方式初始化地图。但是您可以使用当场生成的匿名类:
map.put(getValuesTypes.FUT(), new HashMap<Double, String>() {{
put(1.0, "A");
put(2.0, "B");
}});
though it's not recommended. I would suggest to use Guava's ImmutableMap
:
虽然不推荐。我建议使用番石榴的ImmutableMap
:
map.put(getValuesTypes.FUT(), ImmutableMap.<Double, String>of(1.0, "A", 2.0, "B"));
If a number of pairs is greater than 5
, you should use their builder
:
如果对的数量大于5
,则应使用它们的builder
:
map.put(getValuesTypes.FUT(),
ImmutableMap.<Double, String>builder().put(1.0, "A")/* 5+ puts */.build());
回答by Vikram Jakhar
You can only initialize a new map by using an anonymous class. i.e.
您只能使用匿名类来初始化新地图。IE
new HashMap<K, V>() {{
put(key, value);
put(key, value);
}};
new HashMap<K, V>() {{
put(key, value);
put(key, value);
}};