Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using find function for maps in scala

Tags:

map

scala

I am trying to find a key in a Map, given a value. I am using the 'find' function by not able to figure out the right predicate for it:

val colors = Map(1 -> "red", 2 -> "blue")
def keyForValue(map: Map[Int, String], value: String) = {
    val bool = map.find{map.foreach{map.values(i) == value}}
        bool.key
  }

How do I iterate over the map and find the key when I know the value?

like image 479
Core_Dumped Avatar asked Oct 24 '13 17:10

Core_Dumped


People also ask

How do you access map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.

How do you check if a key exists in a map Scala?

Scala map contains() method with example It checks whether the stated map contains a binding for a key or not. Where, k is the key. Return Type: It returns true if there is a binding for the key in the map stated else returns false.

How is map implemented in Scala?

Per the Scaladoc, “implements immutable maps using a list-based data structure.” As shown in the examples, elements that are added are prepended to the head of the list. Keys of the map are returned in sorted order. Therefore, all traversal methods (such as foreach) return keys in that order.


1 Answers

You use the same kind of predicate as with a List, but keep in mind you're evaluating it over (key,value) pairs, instead of just values (and getting a pair back as well!).

Simple example:

val default = (-1,"")
val value = "red"
colors.find(_._2==value).getOrElse(default)._1
like image 121
mikołak Avatar answered Sep 22 '22 23:09

mikołak