繁体   English   中英

在不同案例类别scala的同一字段中按列表分组

[英]group by list on same field with different case classes scala

如何将包含不同案例类别的两个列表进行分组,但是在两个类别上具有相同的字段:

case class X(a:Long, b:Long, c:Long, d:Long)
case class Y(a:Long, e:Long, f :Long)

val i = List(X(10,10,8,8))
val j = List(Y(10,10,8))

val joined = a++b
joined.groupBy(_.a)

错误:值a不是具有Seri​​alizable的产品的成员

谢谢

害怕不匹配模式:

scala> val joined = (i++j) groupBy { case x: X => x.a case y: Y => y.a }
joined: scala.collection.immutable.Map[Long,List[Product with Serializable]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))

粗暴但应要求:

scala> val joined = ((i++j).asInstanceOf[List[{ def a: Long }]]) groupBy(_.a)
warning: there were 1 feature warning(s); re-run with -feature for details
joined: scala.collection.immutable.Map[Long,List[AnyRef{def a: Long}]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))

要么

scala> val joined = (i++j) groupBy { case x => x.asInstanceOf[{ def a: Long }].a }
warning: there were 1 feature warning(s); re-run with -feature for details
joined: scala.collection.immutable.Map[Long,List[Product with Serializable]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))

生成的集合类型是否特别好?

更新:

(i++j) groupBy (_.asInstanceOf[{ def a: Long }].a)

我想知道IDE是否具有重构功能,“转换为下划线”?

您还可以使用Product特征来提取第一项:

scala> val joined= (i++j).groupBy(_.productIterator.toList.head)
joined: scala.collection.immutable.Map[Any,List[Product with Serializable]] = Map(10 -> List(X(10,10,8,8), Y(10,10,8)))

我用这个解决了

trait genericClass{
    def a:Long

}
case class X(override val a:Long, b:Long, c:Long, d:Long) extends genericClass
case class Y(override val a:Long, e :Long, f :Long) extends genericClass

然后:

val c = (X++Y).groupBy(_.a)

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM