BZapper
BZapper

Reputation: 330

Scala - distinct on list, but with a pick order / priority

Given a list of case class:

case class Entity(name: String, priority: Int)

What's a nice way to find all the unique people, but only pick the highest priority entry (where priority 1 is considered higher than 2), so that:

val l = Seq(Entity("Alex",20), Entity("Alex",3), Entity("Bob", 28)) 

becomes

Seq(Entity("Alex", 3), Entity("Bob", 28))

Upvotes: 0

Views: 438

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31262

  • group by name, and
  • sort by rank
  • pick head

Example,

scala> case class Entity(name: String, priority: Int)
defined class Entity

scala> val input = Seq(Entity("Alex",20), Entity("Alex",3), Entity("Bob", 28), Entity("UPD", 100), Entity("UPD", 100))
input: Seq[Entity] = List(Entity(Alex,20), Entity(Alex,3), Entity(Bob,28), Entity(UPD,100), Entity(UPD,100))

scala> input.groupBy(_.name).map(_._2.sortBy(_.priority).head)
res5: scala.collection.immutable.Iterable[Entity] = List(Entity(UPD,100), Entity(Bob,28), Entity(Alex,3))

Efficient approach would be to get the one with minimum rank as you don't need to sort the whole sequence.

scala> input.groupBy(_.name).map(_._2.minBy(_.priority))
res6: scala.collection.immutable.Iterable[Entity] = List(Entity(UPD,100), Entity(Bob,28), Entity(Alex,3))

Similar questions:

How to get min by value only in Scala Map

how to sort a scala.collection.Map[java.lang.String, Int] by its values?

Upvotes: 2

Related Questions