Kotlin Partition method – split List, Map of Objects example

This Kotlin tutorial shows you example that uses Partition method to split List, Map of Objects.

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:


inline fun  Iterable.partition(
    predicate: (T) -> Boolean
): Pair, List>

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.


val (positive, negative) = List.partition { predicate }

III. Practice

0. Product Class


package com.javasampleapproach.fold

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

1. List


package com.javasampleapproach.partition

fun main(args: Array) {

	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:


--- 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


package com.javasampleapproach.partition

fun main(args: Array) {

	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:


--- 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)


By grokonez | August 29, 2017.

Last updated on April 14, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*