This Kotlin tutorial shows you example that uses Fold
method on List
, Map
of Objects.
Related Post: Kotlin List & Mutable List tutorial with examples
>>> Refer to: JavaSampleApproach.com
I. Technology
– Java 1.8
– Kotlin 1.1.2
II. Overview
1. fold()
We will get total quantity for of Product(name,quantity)
List/Map using fold()
method:
1 2 3 4 5 |
inline fun <T, R> Iterable<T>.fold(initial: R, operation: (acc: R, T) -> R): R { var accumulator = initial for (element in this) accumulator = operation(accumulator, element) return accumulator } |
This function helps to accumulate value starting with initial
value, then apply operation
from left to right to current accumulator value and each element.
2. foldRight()
If you want to apply operation
from right to left, you can use foldRight()
:
1 2 3 4 5 6 7 8 9 10 |
inline fun <T, R> List<T>.foldRight(initial: R, operation: (T, acc: R) -> R): R { var accumulator = initial if (!isEmpty()) { val iterator = listIterator(size) while (iterator.hasPrevious()) { accumulator = operation(iterator.previous(), accumulator) } } return accumulator } |
III. Practice
0. Product Class
1 2 3 4 |
package com.kotlination.fold data class Product(val name: String, val quantity: Int) { } |
1. List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.kotlination.fold fun main(args: Array<String>) { val total = listOf(1, 2, 3, 4, 5).fold(0, { total, next -> total + next }) println("total: " + total) val mul = listOf(1, 2, 3, 4, 5).fold(1, { mul, next -> mul * next }) println("mul: " + mul) val productList = listOf( Product("A", 100), Product("B", 200), Product("C", 300), Product("D", 400), Product("E", 500) ) val quantity = productList.map { it.quantity }.fold(0, { total, next -> total + next }) println("quantity: " + quantity) } |
Result:
1 2 3 |
total: 15 mul: 120 quantity: 1500 |
2. Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.kotlination.fold fun main(args: Array<String>) { val productMap = mapOf( "a" to Product("A", 100), "b" to Product("B", 200), "c" to Product("C", 300), "d" to Product("C", 400), "e" to Product("C", 500) ) val quantity = productMap.map { it.value.quantity }.fold(0, { total, next -> total + next }) println("quantity: " + quantity) } |
Result:
1 |
quantity: 1500 |