是否可以仅对scala映射中与给定条件匹配的特定元素进行分组?
发件人:
val map = Map(((1,true,"case0")->List(1,2,3)), ((2,true,"case0")->List(3,4,5)),
((1,true,"case1")->List(2,4,6)), ((2,false,"case1")->List(3)))
要
Map(((1,true,"nocase")->List(2)), ((2,true,"case0")->List(3,4,5)),
((2,false,"case1")->List(3)))
条件:
key._1应匹配且key._2应为true
答案 0 :(得分:2)
这是方式
map.groupBy(
e => (e._1._1, e._1._2) //group input by key._1 and key._2
).collect{
case e if (e._2.keys.size > 1)=> // if key have more cases(key._3) use "nocase"
(e._1._1, e._1._2, "nocase") -> //Tuple3(Int, Boolean, String)
e._2.values.reduce(_.intersect(_)) //List of common elements
case e => //we have only one key._3 so use as it is
(e._1._1, e._1._2, e._2.map(e=> e._1._3).mkString("")) ->
e._2.values.reduce(_.intersect(_))
}
Map((2,false,case1) -> List(3), (2,true,case0) -> List(3, 4, 5), (1,true,nocase) -> List(2))
答案 1 :(得分:1)
您可以在有条件的基础上执行groupBy
map.groupBy{case (key, value) => if (key._1 == 1) (key._1, key._2) else key }
.map{case (key, elements) => (key, elements.values.reduce(_ intersect _ ))}
在这段代码中,如果键的第一个元素不是1,您将使用整个键(3个元素)进行分组,否则它将仅按键的第一个和第二个元素分组
<强>输出强>:
Map((2,true,case0) -> List(3, 4, 5), (2,false,case1) -> List(3), (1,true) -> List(2))