HashMap.containsValue - What's the point?

前端 未结 7 811
臣服心动
臣服心动 2021-01-04 13:16

I\'ve got a HashMap and I need to fetch an item by its integer value. I notice there\'s a containsValue() function, but it would appear I still have to iterate through the m

7条回答
  •  我在风中等你
    2021-01-04 13:41

    A map maps a key to a value. If you have a value and you know the map contains this value, why do you need the key anymore?

    On the other hand, if you really need the key or you have just a property of the value, you can iterate the entrySet(), check the value and return the key if found:

    for (Map.Entry entry : map.entrySet()) {
      if (entry.getValue().getXy().equals(xy)) {
        return entry.getKey();
      }
    }
    

提交回复
热议问题