Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 map to find the correct index anyway.

My question is; why use containsValue() if I'm required to traverse it afterwards?

Also, am I missing the point completely? ;-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
274 views
Welcome To Ask or Share your Answers For Others

1 Answer

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<Index,Value> entry : map.entrySet()) {
  if (entry.getValue().getXy().equals(xy)) {
    return entry.getKey();
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...