Updated March 31, 2023
Introduction to Kotlin flatMap
The following article provides an outline for Kotlin flatMap. The flatMap is one of the features, and it is used to combine with two different collections, and it returns with the collection with the single list of all elements yielded and retrieved data from the results with applying certain conditions to check on each element of the original collection the elements/items are transformed, and it is emitted by observable into the specified sequences. The list items are of any datatypes like string, integer each value element has to be stored with the separate memory reference and the transferred datas and results of the function being invoked on separate entries of the original map.
Syntax of Kotlin flatMap
In kotlin language, the collections are one of the most important util packages in that some pre-defined classes like map, list etc. The flatMap() is one of the methods that is used to create the single set of list entries from the input results.
fun main(args:Array<String>)
{
val varss= listOf("") // Instead of listOf() method we can use any other collection methods like hashmap etc.
vars.flatMap{
----some logic codes which depends on the user input requirement---
}
}
The above code is the basic syntax for utlising the flatMap() method in the program with kotlin collections.
How flatMap Works in Kotlin?
The flatMap is one of the default methods for implementing the single collection list where it can be converted from other multiple collections. Mainly it transforms the items emitted by the observable into the observables and keeps the data in other similar collection datas like hashmap, list etc. Different collections like map, arraylist are separated, and it is parsed into a single-level set of datas. It may be of string, integer, float, decimal etc. any data type will be supported for this method to store and retrieve the datas.
The flatMap is used to combine with all the collection line items, and datas that can be sequenced with the specific orders each value will have a specific index, and these index ranges are different from each other data type which are used by the collections. Mapping indexed and the filter will most probably be used in the collection package for to filter and reduce the codes; it should be avoided using the boiler-plate codes.
If the use case has been sequenced with transformed data through via using the flatMap, some elements should be ignored so that time we have a workaround for adding the filter before using the flatMap that drawback is it breaks some smart casts. We can use other methods like sequenceOf() method for the elements that are used during the operation performed by the flatMap() method.
Examples of Kotlin flatMap
Given below are the examples of Kotlin flatMap:
Example #1
Code:
package one;
open class Language
{
fun Java()
{
println("Welcome To My Domain Thank you for learning the java language")
}
fun Cpluspluslang()
{
println("Welcome To My Domain Thank you for learning the C++ language")
}
fun Kotlin()
{
println("Welcome To My Domain Thank you for learning the Kotlin language")
}
fun Python()
{
println("Welcome To My Domain Thank you for learning the Python language")
}
fun Go()
{
println("Welcome To My Domain Thank you for learning the Go language")
}
fun Clang()
{
println("Welcome To My Domain Thank you for learning the C language")
}
fun DotNet()
{
println("Welcome To My Domain Thank you for learning the DotNet language")
}
}
fun main(args:Array<String>)
{
val ls1 = listOf("Java", "C", "C++", "Kotlin","Python","Go","DotNet","JavaScript")
println(ls1.flatMap { it.toList() })
val ls2 = listOf("Monday", "Tuesday", "Wednesday", "Thrusday","Friday","Saturday","Sunday")
println(ls2.flatMap { it.toList() })
val ls3 = listOf("January", "February", "March", "April","May","June","July","August","September","October","November","December")
println(ls3.flatMap { it.toList() })
val ls4 = listOf("HP", "Lenovo", "HCL", "Apple","Wipro","Samsung","Thinkpad","Dell")
println(ls4.flatMap { it.toList() })
val ls5 = listOf("Information Technology", "Accounts", "Finance", "Sales and Marketing","Support","Research and Development","Hosting","Management")
println(ls5.flatMap { it.toList() })
}
Output:
In the above example, we used different methods on the class, and we called and used the flatMap() method in the array list collection.
Example #2
Code:
package one;
interface Second {
val sec: Int
fun eg() : String
fun demo() {
println("Welcome To My Domain its the Second example that related to the kotlin FlatMap")
}
}
class secn : Second {
override val sec: Int = 41
override fun eg() = "Have a Nice day users"
}
interface third {
fun eg1() {
println("We have discussed about the kotlin FlatMap on this example")
}
}
interface four {
fun eg2() {
println("Based on the requirement we used list, map and set interfaces and eventhough we used other default collection methods")
}
}
fun main(args: Array<String>) {
val vars = listOf("class","methods","properties", "attributes", "compiler","interpreter")
for(x in vars){
println("Thank you users for spending the time with our application $x,$vars.flatMap { it.toList() }")
}
val vars1 = listOf("pointers","inheritance","polymorphism", "function overloading", "function overriding")
for(y in vars1){
println("Thank you users for spending the time with our application $y,$vars1.flatMap { it.toList() }" )
}
val vars2 = listOf("abstract class","abstract methods","static class", "static methods", "kclass","sealed class")
for(z in vars2){
println("Thank you users for spending the time with our application $z, $vars2.flatMap { it.toList() }" )
}
}
Output:
In the second example, we used classes, interfaces for to implement the user logics and called the flatmap() method in the array lists.
Example #3
Code:
package one;
fun main(args : Array<String>) {
println("Welcome to my domain its the third example that related to the kotlin flatmap")
var vars = setOf(13,26,39,42,"String","Raman")
for(x in vars){
println("$x,vars.flatMap{it.toList()}")
}
val b = setOf(3, 6, 9, 12, 15)
println("If your input numbers are not null values: "+b.mapNotNull
{ if ( it == 1) null else it * 2 })
println("If your input numbers are not null values: "+b.mapIndexedNotNull
{ c, value -> if (c == 0) null else value * c })
val d: Set<Any> = setOf(0,1,2,3,4,5,"siva","raman")
val e = setOf(6,12,18,24,30)
println("Have a nice day users")
for(y in d){
println("$y,e.flatMap{it.toList()}")
}
println("Your input datas are")
println(d.contains("siva"))
println("Your second input datas should be the number format")
println(d.contains(41))
println("Your third input datas should be the numeric characters")
println(d.containsAll(e))
val t: Set<Any> = setOf(5,10,15,20,25,30,"arun","kumar","sasi","jai")
println("Thank you users for spending the time with our application")
for(v in t){
println(v)
}
println("print t.elementAt(4)")
println(t.elementAt(3))
println("print t.elementAtOrNull(5)")
println(t.elementAtOrNull(5))
}
Output:
In the final example, we used the flatMap() method in the setof() collections that will be splitted and displayed the datas in the console.
Conclusion
In kotlin language, we used a different set of classes, methods for to implement the application with user requirements, and most probably, it satisfies the user requirements like both front end and back end. So here, flatMap() is the default method in collections that can be collect the multiple collections into a single one. So it reduces the complexity and increases the performance.
Recommended Articles
This is a guide to Kotlin flatMap. Here we discuss the introduction, syntax, and working of flatMap in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –