Reputation: 74679
How to idiomaticaly search for an value
in a list of (element, value)
pairs in Scala?
Are there better (perhaps more succinct and/or efficient) ways than the following solution?
code.find(_._1 == 2).get._2
where code
is of List[(Int, String)]
type?
scala> val code: List[(Int, String)] = (0, "zero") :: (1, "one") :: (2, "two") :: Nil
code: List[(Int, String)] = List((0,zero), (1,one), (2,two))
scala> code.find(_._1 == 2).get._2
res0: String = two
Upvotes: 3
Views: 1256
Reputation: 340763
What about pattern matching?
code.collectFirst{ case(2, x) => x }
This yields Some(two)
which you can further map
/fold
.
Upvotes: 11
Reputation: 31724
This will do:
scala> code.toMap
res17: scala.collection.immutable.Map[Int,String] = Map(0 -> zero, 1 -> one, 2 -> two)
scala> res17(0)
res18: String = zero
Upvotes: 0