Pradip Karad
Pradip Karad

Reputation: 1427

scala list read value of given string

first list

val l1 = List(("A",12,13),("B",122,123),("C",1212,123))

finding string

val l2 = "A"

If string "A" presents in list then display matching data in above case if string "A" match then output will be 12

else string does not match then shows only 0

Upvotes: 2

Views: 127

Answers (4)

elm
elm

Reputation: 20435

Using a for comprehension the solution may be reformulated as return second element in matching tuples or else and empty list if no matches were found, namely

for ( (s,i,j) <- l1 if s == l2) yield i

which delivers

List(12)

Upvotes: 0

Dennis
Dennis

Reputation: 2665

l1.find(_._1 == l2).map(_._2).getOrElse(0)

or more verbose version

l1.find(a => a._1 == l2).map(a => a._2).getOrElse(0)

Upvotes: 0

thoredge
thoredge

Reputation: 12651

Find first match; retrieve second part of tuplet or 0

 l1.find(_._1 == "A").map(_._2).getOrElse(0)

Upvotes: 4

4lex1v
4lex1v

Reputation: 21567

There is a little nasty rule exists in scala pattern matching, if some variable starts with an Upper case letter the it matches against its value, so you can rename val l2 = "A" to val L2 = "A" the you the following would work -

scala> l1.collectFirst{ case (L2, i, _) => i }.getOrElse(0)
res0: Int = 12

Upvotes: 2

Related Questions