删除具有特定值 Scala 2.11.12 的元组键重复项
Remove tuple key duplicate with certain value Scala 2.11.12
我有一组元组:
Set(("autumn",0), ("winter",2), ("summer",0), ("winter",0), ("spring",0))
如何删除键重复且值为 0 的元组?
结果:
Set(("autumn",0), ("winter",2), ("summer",0), ("spring",0))
在这种特殊情况下,您可以按元组的第一个元素分组,select 第二个元素的最大值:
val values = Set(("autumn",0), ("winter",2), ("summer",0), ("winter",0), ("spring",0))
val result = values
.groupMap(_._1)(_._2) // groups by first element and maps group values to second
.map(t => (t._1, t._2.max))
或者只用 groupBy
:
重用原始值
val result = values
.groupBy(_._1)
.map(_._2.maxBy(_._2))
按元组的第一个元素分组,然后对值进行排序并取第一个元素:
val mySet = Set(("autumn", 0), ("winter", 2), ("summer", 0), ("winter", 0), ("spring", 0))
val result = mySet.groupBy(_._1)
.mapValues(_.toList.sortBy(-_._2).head)
.values.toSet
//scala.collection.immutable.Set[(String, Int)] = Set((winter,2), (autumn,0), (spring,0), (summer,0))
我有一组元组:
Set(("autumn",0), ("winter",2), ("summer",0), ("winter",0), ("spring",0))
如何删除键重复且值为 0 的元组?
结果:
Set(("autumn",0), ("winter",2), ("summer",0), ("spring",0))
在这种特殊情况下,您可以按元组的第一个元素分组,select 第二个元素的最大值:
val values = Set(("autumn",0), ("winter",2), ("summer",0), ("winter",0), ("spring",0))
val result = values
.groupMap(_._1)(_._2) // groups by first element and maps group values to second
.map(t => (t._1, t._2.max))
或者只用 groupBy
:
val result = values
.groupBy(_._1)
.map(_._2.maxBy(_._2))
按元组的第一个元素分组,然后对值进行排序并取第一个元素:
val mySet = Set(("autumn", 0), ("winter", 2), ("summer", 0), ("winter", 0), ("spring", 0))
val result = mySet.groupBy(_._1)
.mapValues(_.toList.sortBy(-_._2).head)
.values.toSet
//scala.collection.immutable.Set[(String, Int)] = Set((winter,2), (autumn,0), (spring,0), (summer,0))