Collections utility: Filtering a list and converting a list to map in Kotlin

In this article, we will learn about Collections utility: How to filter a list and converting a list to map in Kotlin?
Submitted by Aman Gautam, on January 14, 2018

In the previous article we have learn about collections in kotlin and how to implement list, set and, map in Kotlin. Now in this article we will discuss some extra feature of kotlin programming language like filtering and extracting elements from list and converting list into map.

Filtering list

Filtering list is an easy task in kotlin. Sometimes from an immutable list we have to extract some elements but we cannot use add or remove method. In such case we can create a new list by extracting required elements from the original one.

Consider a template,

class player(varname:String,varsport:String)

val favPlayer= listOf( player("MS Dhoni","Cricket"),
player("SainaNehwal","badminton"),
player("V kohli","Cricket"), 
player("DhyanChand","Hockey"))

1) Using filter{}

val crick = favPlayer.filter{it.sport.equals("Cricket")}
for (p in crick){
	println(p.name)	
}

Output

MS Dhoni
V kohli

2) Using map{}

var sports=favPlayer.map{ it.name }
for (p in sports){
	println(p)
}

Output

MS Dhoni
SainaNehwal
V kohli
Dhyan Chand

Converting a list to map

Considering the above example, we can also create a map of a player to his/her sport which would result in relaxed searching etc.

player2sport=favPlayer.associateBy( {it.name},{it.sport})
for ((p,s) in player2sport){
	println(p+" -> "+s)
}

Output

MS Dhoni -> Cricket
SainaNehwal -> badminton
V kohli -> Cricket
Dhyan Chand -> Hockey

So in the last I would say that kotlin has made the Collections to perform better with precise and concise code. It also provides a lot of operations to made the task easy. I have discussed only few of them and more is coming in the further articles. Stay tuned.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.