0

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))
BZapper
  • 320
  • 3
  • 19

1 Answers1

2
  • 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?

prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • awesome! thanks! intelliJ tells me you could further simplify it using minBy(), but thanks seriously – BZapper Feb 07 '18 at 00:47
  • minBy is a nice approach actually because you only care about the minimum, so no overhead of sorting the whole sequence. – prayagupa Feb 07 '18 at 00:50