Java 根据键名从 HashMap 获取字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1789679/
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
get string value from HashMap depending on key name
提问by Jimmy
I have a HashMap
with various keys and values, how can I get one value out?
我有一个HashMap
有各种键和值的,我怎样才能得到一个值?
I have a key in the map called my_code
, it should contain a string, how can I just get that without having to iterate through the map?
我在地图中有一个名为 的键my_code
,它应该包含一个字符串,我怎样才能在不必遍历地图的情况下获得它?
So far I've got..
到目前为止我有..
HashMap newMap = new HashMap(paramMap);
String s = newMap.get("my_code").toString();
I'm expecting to see a String
, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println()
I get something like java.lang.string#F0454
我期待看到一个String
,例如“ABC”或“DEF”,因为这是我最初放在那里的内容,但是如果我做了一个,System.out.println()
我会得到类似的东西java.lang.string#F0454
Sorry, I'm not too familiar with maps as you can probably guess ;)
抱歉,我对地图不太熟悉,你可能猜到了 ;)
采纳答案by BalusC
Just use Map#get(key)
?
就用Map#get(key)
?
Object value = map.get(myCode);
Here's a tutorial about maps, you may find it useful: http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html.
这是关于地图的教程,您可能会发现它很有用:http: //java.sun.com/docs/books/tutorial/collections/interfaces/map.html。
Edit:you edited your question with the following:
编辑:您使用以下内容编辑了您的问题:
I'm expecting to see a String, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454
Sorry, I'm not too familiar with maps as you can probably guess ;)
我期待看到一个字符串,例如“ABC”或“DEF”,因为这是我最初放在那里的内容,但是如果我执行 System.out.println() 我得到类似 java.lang.string# 的东西F0454
抱歉,我对地图不太熟悉,你可能猜到了 ;)
You're seeing the outcome of Object#toString()
. But the java.lang.String
should already have one implemented, unless you created a customimplementation with a lowercase s
in the name: java.lang.string
. If it is actually a custom object, then you need to override Object#toString()
to get a "human readable string" whenever you do a System.out.println()
or toString()
on the desired object. For example:
你看到的结果Object#toString()
。但是java.lang.String
应该已经实现了,除非您创建了一个名称中带有小写字母的自定义实现s
:java.lang.string
。如果它实际上是一个自定义对象,那么Object#toString()
无论何时在所需的对象上执行 aSystem.out.println()
或,都需要覆盖以获取“人类可读的字符串” toString()
。例如:
@Override
public String toString() {
return "This is Object X with a property value " + value;
}
回答by Jon Skeet
Your question isn't at all clear I'm afraid. A key doesn't have a "name"; it's not "called" anything as far as the map is concerned - it's just a key, and will be compared with other keys. If you have lots of different kinds of keys, I strongly suggest you put them in different maps for the sake of sanity.
恐怕你的问题根本不清楚。密钥没有“名称”;就地图而言,它没有被“称为”任何东西——它只是一个键,将与其他键进行比较。如果你有很多不同种类的钥匙,我强烈建议你为了理智起见把它们放在不同的地图上。
If this doesn't help, please clarify the question - preferrably with some code to show what you mean.
如果这没有帮助,请澄清问题 - 最好使用一些代码来显示您的意思。
回答by abyx
map.get(myCode)
map.get(myCode)
回答by raffael
You can use the get(Object key) method from the HashMap. Be aware that i many cases your Key Class should override the equals method, to be a useful class for a Map key.
您可以使用 HashMap 中的 get(Object key) 方法。请注意,在许多情况下,您的 Key 类应该覆盖 equals 方法,以成为 Map 键的有用类。
回答by jeff porter
If you are storing keys/values as strings, then this will work:
如果您将键/值存储为字符串,那么这将起作用:
HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("my_code", "shhh_secret");
String value = newMap.get("my_code");
The question is what gets populated in the HashMap (key & value)
问题是在 HashMap 中填充了什么(键和值)
回答by Shirishkumar Bari
If you will use Generics and define your map as
如果您将使用泛型并将您的地图定义为
Map<String,String> map = new HashMap<String,String>();
then fetching value as
然后取值作为
String s = map.get("keyStr");
you wont be required to typecast the map.get() or call toString method to get String value
您不需要对 map.get() 进行类型转换或调用 toString 方法来获取 String 值
回答by Sreeja Mohan
An important point to be noted here is that if your key is an object of user-defined class in java then make it a point to override the equals method. Because the HashMap.get(Object key) method uses the equals method for matching the key value. If you do not override the equals method then it will try to find the value simply based on the reference of the key and not the actual value of key in which case it will always return a null.
这里要注意的一个重要点是,如果您的键是 Java 中用户定义类的对象,那么请使其成为覆盖 equals 方法的一个点。因为 HashMap.get(Object key) 方法使用 equals 方法匹配键值。如果您不覆盖 equals 方法,那么它将尝试仅根据键的引用而不是键的实际值来查找值,在这种情况下,它将始终返回空值。
回答by Gaurav Sachdeva
Suppose you declared HashMap as :-
假设您将 HashMap 声明为:-
HashMap<Character,Integer> hs = new HashMap<>();
Then,key in map is of type Character data type and value of int type.Now,to get value corresponding to key irrespective of type of key,value type, syntax is :-
那么,map中的key是Character数据类型,value是int类型。现在,不管key的类型,value的类型,获取key对应的值,语法是:-
char temp = 'a';
if(hs.containsKey(temp)){
` int val = hs.get(temp); //val is the value corresponding to key temp
}
So, according to your question you want to get string value corresponding to a key.For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs.get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.
因此,根据您的问题,您想获取与键对应的字符串值。为此,只需将 HashMap 声明为 HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); 使用这将使您的代码更清晰,而且您不必将 hs.get("my_code") 的结果转换为字符串,因为默认情况下,如果在输入时将值保留为字符串,则它返回字符串的值。
回答by Jabar Shahid
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(4, "DD");
The Value mapped to Key 4
is DD
映射到键的值4
是DD
回答by hel
This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:
这是如何使用 keySet()、get()、values() 和 entrySet() 函数获取 Map 中的键和值的另一个示例:
Map<Integer, String> testKeyset = new HashMap<Integer, String>();
testKeyset.put(1, "first");
testKeyset.put(2, "second");
testKeyset.put(3, "third");
testKeyset.put(4, "fourth");
// Print a single value relevant to a specified Key. (uses keySet())
for(int mapKey: testKeyset.keySet())
System.out.println(testKeyset.get(mapKey));
// Print all values regardless of the key.
for(String mapVal: testKeyset.values())
System.out.println(mapVal.trim());
// Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
System.out.println(testKeyset.entrySet());