Balaram26
Balaram26

Reputation: 1389

Way to Extract list of elements from Scala list

I have standard list of objects which is used for the some analysis. The analysis generates a list of Strings and i need to look through the standard list of objects and retrieve objects with same name.

  case class TestObj(name:String,positions:List[Int],present:Boolean)
  val stdLis:List[TestObj]

  //analysis generates a list of strings
  var generatedLis:List[String]

  //list to save objects found in standard list
  val lisBuf = new ListBuffer[TestObj]()

  //my current way
  generatedLis.foreach{i=>
    val temp = stdLis.filter(p=>p.name.equalsIgnoreCase(i))
    if(temp.size==1){
      lisBuf.append(temp(0))
    }
  }

Is there any other way to achieve this. Like having an custom indexof method that over rides and looks for the name instead of the whole object or something. I have not tried that approach as i am not sure about it.

Upvotes: 2

Views: 2177

Answers (2)

j-keck
j-keck

Reputation: 1031

stdLis.filter(testObj => generatedLis.exists(_.equalsIgnoreCase(testObj.name)))
  • use filter to filter elements from 'stdLis' per predicate
  • use exists to check if 'generatedLis' has a value of ....

Upvotes: 3

Sergii Lagutin
Sergii Lagutin

Reputation: 10661

Don't use mutable containers to filter sequences.

Naive solution:

val lisBuf =
  for {
    str <- generatedLis
    temp = stdLis.filter(_.name.equalsIgnoreCase(str))
    if temp.size == 1
  } yield temp(0)

if we discard condition temp.size == 1 (i'm not sure it is legal or not):

val lisBuf = stdLis.filter(s => generatedLis.exists(_.equalsIgnoreCase(s.name)))

Upvotes: 1

Related Questions