Functional calculation of list values

I have 2 lists containing instances of lottery tickets.

In one list there are tickets that won a special prize, and in another list there are tickets that received final numbers.

Now I have to eliminate these redundant tickets 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 will give a list with combined tickets, which themselves contain accumulated prizes:

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

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

+4
source share
1 answer
 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)) 
+9
source

Source: https://habr.com/ru/post/1396276/


All Articles