4

I have 2 Lists containing lottery-ticket instances.

One List holds tickets that won a special prize, the other List contains Tickets that got final-digit-hits.

Now I have to eliminate those tickets with redundant numbers and add the prizes together.

case class Ticket(number:Long, prize:Long)

val specialPrizes    = List(Ticket(42, 1000), Ticket(66, 2000))
val finalDigitPrizes = List(Ticket(42, 50))

This would yield a List with merged Tickets which themselves contain accumulated prizes:

val finalList = List(Ticket(42, 1050), Ticket(66, 2000))

What would be the most effective way to do this functionally without temp-vars, index-counters, etc?

1 Answer 1

9
scala> (specialPrizes ++ finalDigitPrizes).groupBy(_.number).map {
     |   case (n, ts) => Ticket(n, ts.map(_.prize).sum)
     | }
res1: scala.collection.immutable.Iterable[Ticket] = List(Ticket(42,1050), Ticket(66,2000))
Sign up to request clarification or add additional context in comments.

1 Comment

groupBy wins again. I should always use that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.