android kotlin - Sequence partition example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnPartition = findViewById<Button>(R.id.btnPartition)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = generateList()

        btnList.setOnClickListener {
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} : ")
                textView.append("${emp.age} : $${emp.salary}")
            }
        }


        btnPartition.setOnClickListener {
            // Splits the sequence into pair of lists
            val (juniors,seniors) = list.partition {
                it.age<=20
            }

            textView.text = "Employee age <=20:\n"
            // Loop through the juniors employee
            juniors.forEach {
                textView.append("\n${it.name} : ${it.age} : ${it.salary}")
            }

            textView.append("\n\n\nEmployee age >20:\n")
            // Loop through the seniors employee
            seniors.forEach {
                textView.append("\n${it.name} : ${it.age} : ${it.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Elian",24,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Brisa",24,5200))
    list.add(Employee("Clementine",19,4900))
    list.add(Employee("Lauriane",25,2300))
    list.add(Employee("Amy",25,2000))
    list.add(Employee("Lizu",54,5100))
    list.add(Employee("Frederic",20,2600))
    list.add(Employee("Innee",17,4100))
    list.add(Employee("Sabryna",21,5100))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnPartition"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Partition"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - maxBy and maxWith example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnMaxBy = findViewById<Button>(R.id.btnMaxBy)
        val btnMaxWith = findViewById<Button>(R.id.btnMaxWith)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = generateList()

        btnList.setOnClickListener {
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} : ")
                textView.append("${emp.age} : $${emp.salary}")
            }
        }


        btnMaxBy.setOnClickListener {
            // Get the oldest employee from this list
            val maxAge: Employee = list.maxBy { it.age }

            textView.text = "Employee max by age:\n"
            maxAge.apply {
                textView.append("\n${this.name} " +
                        ": ${this.age} : ${this.salary}")
            }
        }


        btnMaxWith.setOnClickListener {
            // Get the employee from this list
            // whose name length is biggest
            val maxLengthName: Employee =
                list.maxWith { emp1, emp2 ->
                emp1.name.length - emp2.name.length
            }

            textView.text = "Employee max with name length:\n"
            maxLengthName.apply {
                textView.append("\n${this.name} " +
                        ": ${this.age} : ${this.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Elian",24,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Brisa",24,5200))
    list.add(Employee("Clementine",19,4900))
    list.add(Employee("Lauriane",25,2300))
    list.add(Employee("Amy",25,2000))
    list.add(Employee("Tristian",54,5100))
    list.add(Employee("Frederic",20,2600))
    list.add(Employee("Innee",25,4100))
    list.add(Employee("Sabryna",54,5100))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnMaxBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="maxBy"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <Button
        android:id="@+id/btnMaxWith"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="maxWith"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnMaxBy"
        app:layout_constraintStart_toEndOf="@+id/btnMaxBy" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - distinctBy multiple fields example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnDistinctBy = findViewById<Button>(R.id.btnDistinctBy)
        val btnDistinctByFields = findViewById<Button>(
            R.id.btnDistinctByFields)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = generateList()

        btnList.setOnClickListener {
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} " +
                        ": age ${emp.age} : salary $${emp.salary}")
            }
        }


        btnDistinctBy.setOnClickListener {
            // Remove the duplicate elements from the list
            // Keep only unique elements in the collection
            // return a new collection instance
            // Remove the duplicate employee from the
            // list which name and age both are same
            val distinctList:List<Employee> = list.distinctBy {
                it.name to it.age }

            textView.text = "Distinct list by name and age:\n"

            // Iterate through the distinct list
            distinctList.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} " +
                        ": age ${emp.age} : salary $${emp.salary}")
            }
        }


        btnDistinctByFields.setOnClickListener {
            // Keep only unique elements in the collection
            // Remove the duplicate employee from the
            // list which name and salary both are same
            val distinctList:List<Employee> = list.distinctBy {
                listOf(it.name,it.salary) }

            textView.text = "Distinct list by name and salary:\n"

            // Iterate through the distinct list
            distinctList.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} " +
                        ": age ${emp.age} : salary $${emp.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Ana",24,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Ana",24,5200))
    list.add(Employee("Clementine",19,4900))
    list.add(Employee("Innee",25,2300))
    list.add(Employee("Amy",25,2000))
    list.add(Employee("Sabryna",29,5100))
    list.add(Employee("Frederic",20,2600))
    list.add(Employee("Innee",25,4100))
    list.add(Employee("Sabryna",27,5100))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="12dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnDistinctBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="distinctBy"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <Button
        android:id="@+id/btnDistinctByFields"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="distinctBy Fields"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnDistinctBy"
        app:layout_constraintStart_toEndOf="@+id/btnDistinctBy" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="22sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - distinctBy example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnDistinctBy = findViewById<Button>(R.id.btnDistinctBy)
        val btnDistinctByAge = findViewById<Button>(
            R.id.btnDistinctByAge)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = generateList()

        btnList.setOnClickListener {
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} " +
                        ": age ${emp.age} : salary $${emp.salary}")
            }
        }

        btnDistinctBy.setOnClickListener {
            // Remove the duplicate elements from the list
            // Keep only unique elements in the collection
            // return a new collection instance
            // Remove the duplicate names employee from the list
            val distinctList:List<Employee> = list.distinctBy { it.name }

            textView.text = "Distinct list by name:\n"

            // Iterate through the distinct list
            distinctList.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} " +
                        ": age ${emp.age} : salary $${emp.salary}")
            }
        }

        btnDistinctByAge.setOnClickListener {
            // Keep only unique elements in the collection
            // Remove the duplicate ages employee from the list
            val distinctList:List<Employee> = list.distinctBy { it.age }

            textView.text = "Distinct list by age:\n"

            // Iterate through the distinct list
            distinctList.forEachIndexed { index, emp ->
                textView.append("\n${index+1}. ${emp.name} " +
                        ": age ${emp.age} : salary $${emp.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Ana",25,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Ana",24,5200))
    list.add(Employee("Clementine",19,4900))
    list.add(Employee("Innee",25,2300))
    list.add(Employee("Amy",25,2000))
    list.add(Employee("Sabryna",16,5100))
    list.add(Employee("Frederic",20,2600))
    list.add(Employee("Innee",25,4100))
    list.add(Employee("Ana",29,6800))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="12dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnDistinctBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="distinctBy"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <Button
        android:id="@+id/btnDistinctByAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="distinctBy Age"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnDistinctBy"
        app:layout_constraintStart_toEndOf="@+id/btnDistinctBy" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="22sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Distinct example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnDistinct = findViewById<Button>(R.id.btnDistinct)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = listOf("RED","GREEN","RED","BLUE",
            "PINK","BLUE","BLACK","BLUE")


        btnList.setOnClickListener {
            textView.text = "List:\n"

            // Iterate through the list
            list.forEachIndexed{ index, s->
                textView.append("\n${index+1}. $s")
            }
        }


        btnDistinct.setOnClickListener {
            // Remove the duplicate elements from the list
            // Keep only unique elements in the collection
            // return a new collection instance
            val distinctList:List<String> = list.distinct()

            textView.text = "Distinct List:\n"

            // Iterate through the distinct list
            distinctList.forEachIndexed { index, s ->
                textView.append("\n${index+1}. $s")
            }
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnDistinct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Distinct"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - List groupBy example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnGroupBy = findViewById<Button>(R.id.btnGroupBy)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = listOf("RED","GREEN","YELLOW","MAGENTA",
            "PINK","WHITE","BLACK","BLUE",
            "SALMON","MAROON","PURPLE")


        btnList.setOnClickListener {
            textView.text = "List:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n$it")
            }
        }


        btnGroupBy.setOnClickListener {
            // Groups the colors by it length
            val groups:Map<Int,List<String>> = list.groupBy {
                it.length
            }

            textView.text = ""
            groups.forEach{
                val length = it.key
                val colors = it.value

                textView.append("\n\n${colors.size} Color(s)" +
                        " length is $length : ")
                colors.forEach {
                    textView.append("$it, ")
                }
            }
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnGroupBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="groupBy"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - joinToString example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnSimple = findViewById<Button>(R.id.btnSimple)
        val btnJoinToString = findViewById<Button>(
            R.id.btnJoinToString)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = listOf("RED","GREEN","YELLOW",
            "MAGENTA","PINK","WHITE")


        btnList.setOnClickListener {
            textView.text = "List:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n$it")
            }
        }


        btnSimple.setOnClickListener {
            // Simply join the list elements to a string
            val joinedString = list.joinToString {
                it.lowercase(Locale.ROOT)
            }
            textView.text = "$joinedString"
        }


        btnJoinToString.setOnClickListener {
            // Join list elements to string in more formatted way
            val convertedString = list.joinToString(
                " | ", // separator
                "[", // prefix
                "]", // postfix
                4, // limit
                "..." // truncated
            ){
                it.lowercase(Locale.ROOT)
            }

            textView.text = "$convertedString"
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSimple"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Simple"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <Button
        android:id="@+id/btnJoinToString"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="joinToString"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnSimple"
        app:layout_constraintStart_toEndOf="@+id/btnSimple" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - forEachIndexed example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnForEachIndexed = findViewById<Button>(
            R.id.btnForEachIndexed)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with values
        val list = listOf("RED","GREEN","YELLOW",
            "MAGENTA","PINK","WHITE")


        btnList.setOnClickListener {
            textView.text = "List:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n$it")
            }
        }


        btnForEachIndexed.setOnClickListener {
            textView.text = "For each indexed:\n"

            // Iterate through the list
            list.forEachIndexed { index, s ->
                // Display both index and value
                textView.append("\n$index : $s")
            }
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnForEachIndexed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="forEachIndexed"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - List of not null example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnNotNullList = findViewById<Button>(
            R.id.btnNotNullList)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        // Create a list with null values
        val list = listOf("Red",null,"Green","Yellow",
            null,"Black","White",null)


        // Create a list which exclude null values
        val notNullList = listOfNotNull("Red",null,
            "Green","Yellow",null,"Black","White",null)


        btnList.setOnClickListener {
            textView.text = "List:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n$it")
            }
        }


        btnNotNullList.setOnClickListener {
            textView.text = "List of not null:\n"

            // Iterate through the not null list
            notNullList.forEach {
                textView.append("\n$it")
            }
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnNotNullList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="Not null list"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - List filter not null example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnFilterNotNull = findViewById<Button>(
            R.id.btnFilterNotNull)
        val btnFilterNotNullTo = findViewById<Button>(
            R.id.btnFilterNotNullTo)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val list = listOf("Red",null,"Green",
            "Yellow",null,"Black","White",null)


        btnList.setOnClickListener {
            textView.text = "List:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n$it")
            }
        }


        btnFilterNotNull.setOnClickListener {
            // Filter nulls value from the list
            // and generate new list
            val filtered = list.filterNotNull()

            textView.text = "Filtered list without null values\n"
            // Iterate through the filtered list
            filtered.forEach {
                textView.append("\n$it")
            }
        }


        btnFilterNotNullTo.setOnClickListener {
            val favColors = mutableListOf("Pink","Olive")

            textView.text = "Favorite colors\n"
            // Iterate through the filtered list
            favColors.forEach {
                textView.append("\n$it")
            }

            // Copy the not null values from the
            // list to favorite colors list
            list.filterNotNullTo(favColors)

            textView.append("\n\nFav colors with another" +
                    " list's non null values\n")
            // Iterate through the filtered list
            favColors.forEach {
                textView.append("\n$it")
            }
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnFilterNotNull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="filterNotnull"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <Button
        android:id="@+id/btnFilterNotNullTo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="filterNotNullT0"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnFilterNotNull"
        app:layout_constraintStart_toEndOf="@+id/btnFilterNotNull" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Sort list with null values example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnNullsFirst = findViewById<Button>(
            R.id.btnNullsFirst)
        val btnNullsLast = findViewById<Button>(
            R.id.btnNullsLast)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val list = mutableListOf("Red",null,"Green","Yellow",
            null,"Black","White",null)


        btnList.setOnClickListener {
            textView.text = "List:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n$it")
            }
        }


        btnNullsFirst.setOnClickListener {
            list.sortWith(
                nullsFirst(
                    compareBy{
                        it
                    }
                )
            )

            textView.text = "Nulls first and ascending order\n"
            // Iterate through the sorted list
            list.forEach {
                textView.append("\n$it")
            }
        }


        btnNullsLast.setOnClickListener {
            list.sortWith(
                nullsLast(
                    compareByDescending{
                        it
                    }
                )
            )

            textView.text = "Nulls last and descending order\n"
            // Iterate through the sorted list
            list.forEach {
                textView.append("\n$it")
            }
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnNullsFirst"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Nulls First"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <Button
        android:id="@+id/btnNullsLast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Nulls Last"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnNullsFirst"
        app:layout_constraintStart_toEndOf="@+id/btnNullsFirst" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - List sort multiple fields by both orders

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnSort = findViewById<Button>(R.id.btnSort)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        btnList.setOnClickListener {
            val list = generateList()
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }


        btnSort.setOnClickListener {
            val list = generateList()

            // List sort by multiple fields
            list.sortWith(
                compareBy<Employee>{
                    // Name in ascending order
                    it.name
                }.thenByDescending {
                    // Then age in descending order
                    it.age
                }
            )

            textView.text = "Sort name ASC and age DESC order\n"
            // Iterate through the sorted list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Weston",25,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Ana",24,5200))
    list.add(Employee("Raymond",19,4900))
    list.add(Employee("Uriel",20,2300))
    list.add(Employee("Amy",19,4650))
    list.add(Employee("Toya",16,5100))
    list.add(Employee("Amy",20,2600))
    list.add(Employee("Innee",48,4100))
    list.add(Employee("Isaias",16,6800))
    list.add(Employee("Raymond",48,4500))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSort"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Sort ASC DESC Multiple Fields"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - List sort descending using multiple fields

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnSort = findViewById<Button>(R.id.btnSort)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        btnList.setOnClickListener {
            val list = generateList()
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }


        btnSort.setOnClickListener {
            val list = generateList()

            // List descending sort by multiple fields
            list.sortWith(
                compareByDescending<Employee>{
                    it.age
                }.thenByDescending {
                    it.name
                }
            )

            textView.text = "Descending order by age and name\n"
            // Iterate through the sorted list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Weston",25,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Ana",24,5200))
    list.add(Employee("Ashly",19,4900))
    list.add(Employee("Uriel",20,2300))
    list.add(Employee("Amy",19,4650))
    list.add(Employee("Toya",16,5100))
    list.add(Employee("Amy",20,2600))
    list.add(Employee("Innee",48,4100))
    list.add(Employee("Isaias",16,6800))
    list.add(Employee("Raymond",48,4500))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSort"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Sort DESC Multiple Fields"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Sort list using comparator example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnSortWith = findViewById<Button>(R.id.btnSortWith)
        val btnSortWithDesc = findViewById<Button>(
            R.id.btnSortWithDesc)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        btnList.setOnClickListener {
            val list = generateList()
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }


        btnSortWith.setOnClickListener {
            val list = generateList()

            // Sort ascending by comparing employee name length
            list.sortWith(
                Comparator{emp1,emp2->
                    emp1.name.length - emp2.name.length
                }
            )

            textView.text = "emp1.name.length - emp2.name.length\n"
            // Iterate through the sorted list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }


        btnSortWithDesc.setOnClickListener {
            val list = generateList()

            // Sort descending by comparing employee name length
            list.sortWith(
                Comparator{emp1,emp2->
                    emp2.name.length - emp1.name.length
                }
            )

            textView.text = "emp2.name.length - emp1.name.length\n"
            // Iterate through the sorted list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Weston",25,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Ana",24,5200))
    list.add(Employee("Clementine",19,4900))
    list.add(Employee("Uriel",20,2300))
    list.add(Employee("Amy",23,2000))
    list.add(Employee("Sabryna",16,5100))
    list.add(Employee("Frederic",20,2600))
    list.add(Employee("Innee",48,4100))
    list.add(Employee("Isaias",16,6800))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSortWith"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="sortWith"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <Button
        android:id="@+id/btnSortWithDesc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="sortWith Desc"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnSortWith"
        app:layout_constraintStart_toEndOf="@+id/btnSortWith" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>

Android Kotlin: How to sort a complex List by multiple fields

This code demonstrates sorting a list of employees by age and then name in an Android application written in Kotlin. It utilizes buttons to trigger displaying the unsorted list and the sorted list with details like name, age, and salary.

Breakdown:

  1. The MainActivity class handles the activity lifecycle and UI interaction.
  2. It defines a generateList function that creates a list of Employee objects with names, ages, and salaries.
  3. The Employee data class represents an employee with these attributes.
  4. The layout file (activity_main.xml) defines the user interface elements - two buttons and a text view.

There are two button click listeners:

  • "List" button:
    • Generates an employee list.
    • Iterates through the list and displays employee details in the text view.
  • "sortWith" button:
    • Generates an employee list.
    • Sorts the list by age first and then by name using the sortWith function with compareBy extension.
    • Iterates through the sorted list and displays employee details again.

Summary

This code showcases sorting a complex list of employee objects in an Android app. It demonstrates list generation, data class usage, UI interaction with buttons, and sorting a list with multiple criteria using Kotlin's built-in functions.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)
        val btnList = findViewById<Button>(R.id.btnList)
        val btnSortWith = findViewById<Button>(R.id.btnSortWith)


        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        btnList.setOnClickListener {
            val list = generateList()
            textView.text = "Employees:\n"

            // Iterate through the list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }


        btnSortWith.setOnClickListener {
            val list = generateList()

            // List sort by multiple fields
            list.sortWith(
                compareBy({it.age},{it.name})
            )

            textView.text = "compareBy({it.age},{it.name})\n"
            // Iterate through the sorted list
            list.forEach {
                textView.append("\n${it.name} : age ${it.age} " +
                        ": salary $${it.salary}")
            }
        }
    }
}



// Method to generate employee list
private fun generateList():MutableList<Employee>{
    val list = mutableListOf<Employee>()
    list.add(Employee("Weston",25,6500))
    list.add(Employee("Gregg",29,5400))
    list.add(Employee("Ana",24,5200))
    list.add(Employee("Ashly",19,4900))
    list.add(Employee("Uriel",20,2300))
    list.add(Employee("Amy",23,4650))
    list.add(Employee("Toya",16,5100))
    list.add(Employee("Amy",20,2600))
    list.add(Employee("Innee",48,4100))
    list.add(Employee("Isaias",16,6800))
    return list
}


// Data class for Employee
data class Employee(
    val name:String,
    val age:Int,
    val salary:Int
)
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <Button
        android:id="@+id/btnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSortWith"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="sortWith"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="@+id/btnList"
        app:layout_constraintStart_toEndOf="@+id/btnList" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnList" />

</androidx.constraintlayout.widget.ConstraintLayout>