0
votes

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??

2
.filter(_._1 == name2)? - Dmitry Ginzburg
Should the output be List(name2,333,22) or really List((name2,333,22)) ? - Michael Zajac
It should be List(name2,333,22) - Vishwas
Although this problem is solveable, it can be much easier and cleaner if you don't mix types in a List. May be there is another way to construct this List so that it is of type: List[(String, Int, Int)], not List[Any]. - ka4eli

2 Answers

6
votes
.find(_._1 == name2)

will be better

4
votes

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.