JAVA:如何搜索地图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15800606/
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
JAVA: How to search a map?
提问by user2242203
I have a Map that has Strings for its keys and sets (that contain integers) for its values
我有一个 Map,它的键有字符串,值有集合(包含整数)
Say my keys look like this "apple", "banana", "orange", etc.
假设我的键看起来像“苹果”、“香蕉”、“橙色”等。
The user enters text and I save it as a String variable. How do I search my map for an identical key? So if the user types in "apple" how do I give that String to a method and have the method search my map for the "apple" key and return the set of Integers associated with it (values)?
用户输入文本,我将其保存为字符串变量。如何在我的地图中搜索相同的密钥?因此,如果用户输入“apple”,我该如何将该字符串提供给一个方法,并让该方法在我的地图中搜索“apple”键并返回与之关联的一组整数(值)?
Thanks
谢谢
回答by Boris the Spider
You don't really searcha Map, you retrieve values from it thus:
您并没有真正搜索Map,而是从中检索值:
public static void main(String[] args) {
final Map<String, Set<Integer>> myMap = new HashMap<>();
//put new values into map
myMap.put("MyString", new HashSet<Integer>());
//get Set from Map
final Set<Integer> mySet = myMap.get("myString");
}
回答by user2242801
return the set of Integersassociated with it (values)?
返回与之关联的整数集(值)?
A map requires the keys to be different, hence I assume that your map declaration would look like Map<String, List<Integer>> myMap
地图要求键不同,因此我假设您的地图声明看起来像 Map<String, List<Integer>> myMap
To check if a key exists in a Map:
myMap.containsKey(key)
e.g.
myMap.containsKey("apple")
检查地图中是否存在键:
myMap.containsKey(key)
例如
myMap.containsKey("apple")
To get the values associated with the key:
myMap.get(key)
e.g.
myMap.get("apple")
获取与键关联的值:
myMap.get(key)
例如
myMap.get("apple")