Vishwas
Vishwas

Reputation: 7067

How to get list elements by matching string using scala?

I have following list-

List((name1,233,33),(name2,333,22),(name3,444,55),())

I have another string which I want to match with list and get matched elements from list. There will be only one element in list that matches to given string.

The list may contains some empty elements as given as last element in above list.

Suppose I am maching string 'name2' which will occurs only once in the list, then My expected output is -

List(name2,333,22)

How do I find matching list element using scala??

Upvotes: 0

Views: 124

Answers (2)

elm
elm

Reputation: 20435

Consider collect over the tuples list, for instance like this,

val a = List(("name1",233,33),("name2",333,22),("name3",444,55),())

Then

a collect {
  case v @ ("name2",_,_) => v
}

If you want only the first occurrence, use collectFirst. This partial function ignores tuples that do not include 3 items.

Upvotes: 4

Evgeny Vanslov
Evgeny Vanslov

Reputation: 73

.find(_._1 == name2)

will be better

Upvotes: 6

Related Questions