DEV Community

loizenai
loizenai

Posted on

Kotlin sum() and sumBy() method for List, Map of Objects example

https://grokonez.com/kotlin/kotlin-sum-sumby-method-list-map-objects-example

Kotlin sum() and sumBy() method for List, Map of Objects example

This Kotlin tutorial shows you example that uses sum() and sumBy() method for List, Map of Objects.

I. Technology

  • Java 1.8
  • Kotlin 1.1.2

    II. Overview

    The goal is to calculate total quantity of all Product(name, quantity) objects in List/Map using:
  • sum() method: Firstly, map() will create a List of quantity first, then we invoke:
    
    List.sum()
    
  • sumBy() method: It can apply on List of Product, but we must provide selector for indicating quantity:
    
    List.sumBy(selector: product -> quantity)
    

    III. Practice

    0. Product Class

    
    package com.javasampleapproach.fold

data class Product(val name: String, val quantity: Int) {
}

https://grokonez.com/kotlin/kotlin-sum-sumby-method-list-map-objects-example

Kotlin sum() and sumBy() method for List, Map of Objects example

Top comments (0)