我有一个Map,它的键包含字符串,并为其值设置(包含整数)
说我的钥匙看起来像这个“苹果”,“香蕉”,“橙色”等 .
用户输入文本并将其保存为String变量 . 如何在 Map 中搜索相同的密钥?因此,如果用户输入“apple”,我该如何将String提供给方法并让方法在 Map 中搜索“apple”键并返回与之关联的整数集(值)?
谢谢
使用get方法
Set<Integer> values = map.get("apple");
你没有真正搜索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"); }
返回与之关联的整数集(值)?
Map 要求键不同,因此我假设您的 Map 声明看起来像 Map<String, List<Integer>> myMap
Map<String, List<Integer>> myMap
检查 Map 中是否存在密钥: myMap.containsKey(key) 例如 myMap.containsKey("apple")
myMap.containsKey(key)
myMap.containsKey("apple")
要获取与密钥关联的值: myMap.get(key) ,例如 myMap.get("apple")
myMap.get(key)
myMap.get("apple")
3 回答
使用get方法
你没有真正搜索Map,你可以从中检索值:
Map 要求键不同,因此我假设您的 Map 声明看起来像
Map<String, List<Integer>> myMap
检查 Map 中是否存在密钥:
myMap.containsKey(key)
例如myMap.containsKey("apple")
要获取与密钥关联的值:
myMap.get(key)
,例如myMap.get("apple")