How to summarize based on the first Tuples element?

I have a list of 3 tuples, as shown below. [I added line breaks for readability]:

(2, 127, 3)
(12156, 127, 3)
(4409, 127, 2) <-- 4409 occurs 2x
(1312, 127, 12) <-- 1312 occurs 3x

(4409, 128, 1) <-- 
(12864, 128, 1)
(1312, 128, 1) <-- 
(2664, 128, 2)

(12865, 129, 1)
(183, 129, 1)
(12866, 129, 2)
(1312, 129, 10) <--

I want to summarize based on the first entry. The first entry must be unique.

The result should look like this:

(2, 127, 3)
(12156, 127, 3)
(4409, 127, 3) <- new sum = 3
(1312, 127, 23) <- new sum = 23

(12864, 128, 1)
(2664, 128, 2)

(12865, 129, 1)
(183, 129, 1)
(12866, 129, 2)

How can I achieve this in Scala?

+5
source share
3 answers

Try the following:

list groupBy {_._1} mapValues {v => (v.head._1, v.head._2, v map {_._3} sum)}

The average record is saved and always takes the first place that appears in the input list.

+6
source

If you can just ignore the middle record, then:

val l = List(('a,'e,1), ('b,'f,2), ('a,'g,3), ('b,'h,4))
l.groupBy(_._1).mapValues(_.map(_._3).sum) 
// Map('b -> 6, 'a -> 4)

If you need to keep the middle entry:

l.groupBy(_._1).map { 
  case (_, values) =>
    val (a,b,_) = values.head
    (a, b, values.map(_._3).sum)
} 
// List(('b,'f,6), ('a,'e,4))
+3
source

. , .

Once you have a card, you can do the following: The best way to combine two cards and summarize the values โ€‹โ€‹of the same key?

0
source

All Articles