[英]Get Key from Value from Singleton Map - Java
I am looking to retrieve key from the value for a SingletonMap 我正在寻找从SingletonMap的值中检索键
Map<String,String> map = Collections.singletonMap("key1", "value1");
I am looking for a easy way to get the key, based on value. 我正在寻找一种基于价值的简单方法来获取密钥。 Rather then way that I have done before.
而不是我以前做过的方式。 Which I feel is too much overhead for a singleTon Map.
对于singleTon Map,我觉得这太多了。
public static List<String> getKey(String value, Map<String, String> map)
{
List<String> keys = new ArrayList<String>();
for(Entry<String, String> entry:map.entrySet())
{
if(value.equals(entry.getValue()))
{
keys.add(entry.getKey());
}
}
return keys;
}
Any inputs or suggestion will be helpful. 任何意见或建议都会有所帮助。
A singleton map has exactly one entry in it, so you can just do this: 单例地图中只有一个条目,因此您可以执行以下操作:
Map<String,String> map = Collections.singletonMap("key1", "value1");
String theOnlyKeyInTheMap = map.keySet().iterator().next();
I am not sure why do you want this, however I do not think that is possible in any other way. 我不确定为什么要这样做,但是我认为这不可能以其他任何方式实现。 You may be able to make the code readable using something like the Guava Maps.transformEntries call, supplied with a proper transformer function.
您可以使用适当的转换器函数附带的Guava Maps.transformEntries调用使代码可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.