你可以使用 groupBy 和 asInstanceOf,虽然这有点不安全(它可能会抛出):
@ result.groupBy(_(0).asInstanceOf[PersonObj])
res11: Map[PersonObj, List[List[Product with Serializable with Object]]] = Map(
PersonObj("Tiffanny", 32) -> List(List(PersonObj("Tiffanny", 32), LikesOrder("toys", 1), ItemLiked("figurerine", 23))),
PersonObj("John", 23) -> List(
List(PersonObj("John", 23), LikesOrder("toys", 1), ItemLiked("figurerine", 23)),
List(PersonObj("John", 23), LikesOrder("toys", 2), ItemLiked("figurerine", 32))
)
)
然后您可以展平这些值,以便为每个 PersonObj 留下总和列表:
@ result.groupBy(_(0).asInstanceOf[PersonObj]).mapValues(_.flatten)
res12: Map[PersonObj, List[Product with Serializable with Object]] = Map(
PersonObj("Tiffanny", 32) -> List(PersonObj("Tiffanny", 32), LikesOrder("toys", 1), ItemLiked("figurerine", 23)),
PersonObj("John", 23) -> List(
PersonObj("John", 23),
LikesOrder("toys", 1),
ItemLiked("figurerine", 23),
PersonObj("John", 23),
LikesOrder("toys", 2),
ItemLiked("figurerine", 32)
)
)
最后你可以只过滤掉ItemLiked:
@ result.groupBy(_(0).asInstanceOf[PersonObj]).mapValues(_.flatten.filter(_.isInstanceOf[ItemLiked]))
res13: Map[PersonObj, List[Product with Serializable with Object]] = Map(
PersonObj("Tiffanny", 32) -> List(ItemLiked("figurerine", 23)),
PersonObj("John", 23) -> List(ItemLiked("figurerine", 23), ItemLiked("figurerine", 32))
)