0

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

4
  • 4
    .filter(_._1 == name2)? Commented Nov 11, 2014 at 10:03
  • 1
    Should the output be List(name2,333,22) or really List((name2,333,22)) ? Commented Nov 11, 2014 at 14:04
  • It should be List(name2,333,22) Commented Nov 12, 2014 at 4:42
  • 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]. Commented Nov 12, 2014 at 21:15

2 Answers 2

6
.find(_._1 == name2)

will be better

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.