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("V kohli","Cricket"), 

1) Using filter{}

val crick = favPlayer.filter{"Cricket")}
for (p in crick){


MS Dhoni
V kohli

2) Using map{}

var{ }
for (p in sports){


MS Dhoni
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( {},{})
for ((p,s) in player2sport){
	println(p+" -> "+s)


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!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.