I'm learning Scala and attempting to filter Map[String, List[Double]] such that within each sliding window of size 2 if the values are less than .1 then the key values map is returned.
For this data:
val data : Map[String, List[Double]] = Map(
"a" -> List(0.086, 0.086, 0.398, -0.312, 0.312, 0.312, 0.312, 0.312, 0.312, 0.312),
"b" -> List(-0.119, -0.119, 1.007, 1.201, 1.201, 1.201, -1.201, 1.201, 1.201, 1.201))
The Maps: "
"a" -> List(0.086, 0.086)
"b" -> List(-0.119, -0.119)
should be returned as both elements of the List are < .1
I create a sliding window of size 2 :
val sliding = data.map(l => l._2.sliding(2).toList)
sliding contains:
List(List(List(0.086, 0.086), List(0.086, 0.398), List(0.398, -0.312), List(-0.312, 0.312), List(0.312, 0.312), List(0.312, 0.312), List(0.312, 0.312), List(0.312, 0.312), List(0.312, 0.312)), List(List(-0.119, -0.119), List(-0.119, 1.007), List(1.007, 1.201), List(1.201, 1.201), List(1.201, 1.201), List(1.201, -1.201), List(-1.201, 1.201), List(1.201, 1.201), List(1.201, 1.201)))
But using sliding in this way means I've dropped the key's and I'm unsure how to filter this new data structure.
How do filter the values from data? I think I'm over complicating the solution with my use of sliding and that I could using pattern matching instead ?
Update:
Using below code satisfies the condition and produces expected output:
val data : Map[String, List[Double]] = Map(
"a" -> List(0.086, -0.398, -0.398, -0.312, 0.312, 0.312, 0.312, 0.312, 0.312, 0.312),
"b" -> List(-0.119, -0.119, 1.007, 1.201, 1.201, 1.201, -1.201, 1.201, -1.201, -1.201)
)
val result = data.map {
case (key, value) => key -> value.sliding(2).filter(_.forall(_ < .1)).toList
}.filter {
case (_, values) => values.nonEmpty
}
println("result "+result)
Which prints:
Map(a -> List(List(0.086, -0.398), List(-0.398, -0.398), List(-0.398, -0.312)), b -> List(List(-0.119, -0.119), List(-1.201, -1.201)))