Find minimum and maximum values in a list of objects in Kotlin
Given a list of objects, find minimum and maximum values in a list of objects in Kotlin.
1. Using minWith() & maxWith() function
The recommended solution is to find the minimum value in the list of objects is with the minWith() function that accepts a Comparator to compare objects based on a field value. Similarly, to find the maximum value in the list, you can use the maxWith() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
data class Emp(var name: String, var age: Int) fun main() { val list = listOf(Emp("Vicki", 15), Emp("Mike", 10), Emp("Frank", 12)) // get an employee with a minimum age val minAgeEmp = list.minWith(Comparator.comparingInt {it.age }) println("Minimum : $minAgeEmp") // get an employee with a maximum age val maxAgeEmp = list.maxWith(Comparator.comparingInt { it.age }) println("Maximum : $maxAgeEmp") } |
Output:
Minimum : Emp(name=Mike, age=10)
Maximum : Emp(name=Vicki, age=15)
2. Using Reduce Operation
Alternatively, you can perform the reduction operation on the list objects using the reduce() function that takes the comparison object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
data class Emp(var name: String, var age: Int) internal object Compare { fun min(a: Emp, b: Emp): Emp { return if (a.age < b.age) a else b } fun max(a: Emp, b: Emp): Emp { return if (a.age > b.age) a else b } } fun main() { val list = listOf(Emp("Vicki", 15), Emp("Mike", 10), Emp("Frank", 12)) // get an employee with a minimum age val minAgeEmp = list.reduce(Compare::min) println("Minimum : $minAgeEmp") // get an employee with a maximum age val maxAgeEmp = list.reduce(Compare::max) println("Maximum : $maxAgeEmp") } |
Output:
Minimum : Emp(name=Mike, age=10)
Maximum : Emp(name=Vicki, age=15)
That’s all about finding the minimum and maximum values in a list of objects in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)