How to sum several elements after grouping in Kotlin

I have a list of A ( alist) objects .

A { 
  val b : Int
  val c1 : Int
  val c2 : Int
  val d1 : Int
  val d2 : Int
}

and I want to group them band to calculate the amount c1+c2and d1+d2for each group and put the results in a list of objects E elist.

E {
  val sum_of_c_types : Int
  val sum_of_d_types : Int
}

How to reach in kotlin using any built-in collection function?

Note:

I know that I can do this with a function reduceand create temporary objects A, but it is important not to use temporary object A in the code.

+3
source share
3 answers

I solved this using sequence groupBy, mapand sumBy. This is probably not the cleanest solution I guess.

data class A(val b: Int,
             val c1: Int,
             val c2: Int,
             val d1: Int,
             val d2: Int)

data class E(val sumC: Int, val sumD: Int)

fun main(args: Array<String>) {
    val alist = listOf(A(1, 2, 1, 4, 5), A(1, 3, 4, 6, 3), A(2, 2, 2, 2, 2), A(3, 1, 2, 1, 2))
    val grouped: Map<Int, E> = alist.groupBy(A::b).mapValues {
        E(it.value.sumBy { it.c1 + it.c2 }, it.value.sumBy { it.d1 + it.d2 })
    }
    grouped.forEach {
        println("Group b=${it.key}: ${it.value}")
    }
}

Results in:

Group b=1: E(sumC=10, sumD=18)
Group b=2: E(sumC=4, sumD=4)
Group b=3: E(sumC=3, sumD=3)

Edit

Grouping ( groupingBy groupBy), , :

 val grouped = alist.groupingBy(A::b).aggregate { _, acc: E?, e, _ ->
        E((acc?.sumC ?: 0) + e.c1 + e.c2, (acc?.sumD ?: 0) + e.d1 + e.d2)
    }
+4

,

fun group(a: List<A>) = a.groupingBy(A::b).fold(E(0, 0),
        { acc, elem ->
            E(acc.sum_of_c_types + elem.c1 + elem.c2,
                    acc.sum_of_d_types + elem.d1 + elem.d2)
        })
+2

I solved this by running the following code:

alist.groupby { b }. mapValues {
   it.value.map {
      E(it.c1+it.c2, it.d1+it.d2)
   }.reduce { 
      acc, e -> E(acc.sum_of_c_types + e.sum_of_c_types, acc.sum_of_d_types + e.sum_of_d_types)
   }.values
+1
source

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


All Articles