Home > Net >  Remove tuple key duplicate with certain value Scala 2.11.12
Remove tuple key duplicate with certain value Scala 2.11.12

Time:12-25

I have a set of tuples:

Set(("autumn",0), ("winter",2), ("summer",0), ("winter",0), ("spring",0))

How can I remove the tuple which is an key duplicate and has the value 0?

Result:

Set(("autumn",0), ("winter",2), ("summer",0), ("spring",0))

CodePudding user response:

In this particular case you can group by first element of tuple and select maximum for second one:

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))

Or reusing original values with just groupBy:

val result = values
    .groupBy(_._1)
    .map(_._2.maxBy(_._2))

CodePudding user response:

Group by the first element of the tuples then sort the values and take first element:

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))
  • Related