首页 文章

JAVA:如何搜索 Map ?

提问于
浏览
0

我有一个Map,它的键包含字符串,并为其值设置(包含整数)

说我的钥匙看起来像这个“苹果”,“香蕉”,“橙色”等 .

用户输入文本并将其保存为String变量 . 如何在 Map 中搜索相同的密钥?因此,如果用户输入“apple”,我该如何将String提供给方法并让方法在 Map 中搜索“apple”键并返回与之关联的整数集(值)?

谢谢

3 回答

  • 5

    使用get方法

    Set<Integer> values = map.get("apple");
    
  • 2

    你没有真正搜索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");
    }
    
  • 1

    返回与之关联的整数集(值)?

    Map 要求键不同,因此我假设您的 Map 声明看起来像 Map<String, List<Integer>> myMap

    检查 Map 中是否存在密钥: myMap.containsKey(key) 例如 myMap.containsKey("apple")

    要获取与密钥关联的值: myMap.get(key) ,例如 myMap.get("apple")

相关问题