4

I am searching for an efficient way to check if a value exists in Golang. The way I know is using a for loop/ range. Is there a better way to do the same?

Any help would be appreciated :)

Dinesh Auti
  • 89
  • 1
  • 3
  • 8
  • 4
    The question is confusing - you say you want to know if a map contains a *value*, but you compare to Java's `containsKey`, which checks if a map contains a *key*. Which are you looking for? – Adrian Nov 09 '17 at 22:22
  • 1
    If you're looking for how to tell that a key exists, the answer is here: https://stackoverflow.com/questions/2050391/how-to-check-if-a-map-contains-a-key-in-go – Timothy Jones Nov 09 '17 at 22:23
  • @Adrian .. Apologies for the confusion. I have edited the question. – Dinesh Auti Nov 09 '17 at 22:26
  • 1
    @TimothyJones I have the value and check if the value exists in the map and if yes, then extract the key – Dinesh Auti Nov 09 '17 at 22:27

3 Answers3

9

When you index a map in Go you get two return values; the second one (which is optional) is a boolean that indicates if the key exists.

If the key doesn’t exist, the first value will be the default zero value.

Use second return value directly in an if statement.

m := map[string]float64{"pi": 3.14}
if v, found := m["pi"]; found {
    fmt.Println(v)
}
Titanio Yudista
  • 241
  • 4
  • 8
7

There is no built in way to find out if a map contains a particular value. If you need this behaviour to be efficient, consider using an additional data structure to support it.

Note that although Java's Map provides containsValue, the documentation says:

This operation will probably require time linear in the map size for most implementations of the Map interface.

So, if you need an efficient implementation for a Java Map, you also need to provide one.

What "an efficient implementation" means changes based on what kind of data you're mapping. For example, if values are always unique, then maintaining a map[value]key is enough). If they're not, then something more principled is needed.

Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
0

If you have rather big map and want to optimize value checking then add one more map nearly. Likemap[valueType]int. Then:

for k, v := range m {
    values[v]++
}
Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59