Scala - using a pattern matching filter

I have the following lists:

case class myPair(ids:Int,vals:Int)

val someTable = List((20,30), (89,90), (40,65), (45,75), (35,45))

val someList:List[myPair] =
  someTable.map(elem => myPair(elem._1, elem._2)).toList

I would like to filter out all the "ids"> 45. I tried something like this article filter using pattern matching ):

someList.filter{ case(myPair) => ids >= 45 }

but without success. Appreciate your help.

+5
source share
4 answers

Pattern matching is not required at all; the type is known at compile time:

someList.filter(_.ids >= 45)

or a little more verbose / readable:

someList.filter(pair => pair.ids >= 45)
+17
source

Do you mean:

someList.filter{ case MyPair(ids,vals) => ids >= 45 }

myPair myPair, , , , , , ids vals . - , @RandallSchulz.

(1):

val someList = someTable.map(case (ids,vals) => MyPair(ids,vals)).toList

(2):

val someList = someTable.map(elem => MyPair.tupled(elem)).toList

(3):

val someList = someTable.map(MyPair.tupled).toList

, (1) . (2) (3) MyPair.apply(Int,Int) Tuple [Int, Int].

+4

someTable collect {case (i, v) if i > 45 => MyPair(i, v)}

.

+2
case class myPair(ids:Int,vals:Int)

val someTable = List((20,30), (89,90), (40,65), (45,75), (35,45))

val someList:List[myPair] = for( elem <- someTable; if elem._1 > 45) yield myPair(elem._1, elem._2)

someList: List[myPair] = List(myPair(89,90))
0

All Articles