This Kotlin tutorial shows you example that uses Partition
method to split 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
– We will split List/Map of Product(name,quantity)
objects into 2 Lists using partition()
method:
1 2 3 |
inline fun <T> Iterable<T>.partition( predicate: (T) -> Boolean ): Pair<List<T>, List<T>> |
predicate
is the condition for the first List of Pair
, all remain items will be contained in the second List.
– We also use Destructuring Declaration syntax to destructure the Pair
into 2 Lists.
1 |
val (positive, negative) = List.partition { predicate } |
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 |
package com.kotlination.partition fun main(args: Array<String>) { val productList = listOf( Product("A", 100), Product("B", 200), Product("C", 300), Product("D", 400), Product("E", 500) ) val (from250, lessThan250) = productList.partition { it.quantity >= 250 } println("--- from250 ---") from250.forEach { println(it) } println("--- lessThan250 ---") lessThan250.forEach { println(it) } } |
Result:
1 2 3 4 5 6 7 |
--- from250 --- Product(name=C, quantity=300) Product(name=D, quantity=400) Product(name=E, quantity=500) --- lessThan250 --- Product(name=A, quantity=100) Product(name=B, quantity=200) |
2. Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.kotlination.partition 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 (lessThan350, from350) = productMap.map { it.value }.partition { it.quantity < 350 } println("--- lessThan350 ---") lessThan350.forEach { println(it) } println("--- from350 ---") from350.forEach { println(it) } } |
Result:
1 2 3 4 5 6 7 |
--- lessThan350 --- Product(name=A, quantity=100) Product(name=B, quantity=200) Product(name=C, quantity=300) --- from350 --- Product(name=C, quantity=400) Product(name=C, quantity=500) |