Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get min/max from ArrayList based on its object attribute values?

What I want to achieve is to get min/max attribute value of object from ArrayList<Object>. For example if Object has attribute weight(float), I want heaviest object from the list.

I've tried to implement Comparable to get max/min value but this returns same value for min and same for max for some reason. (I don't know if it works with floats)

    val maxVal: Float = arrayList.max().floatVal1
    val minVal: Float = arrayList.min().floatVal1

    data class CustomObject(var val1: String, var floatVal1: Float , var floatVal2: Float?, var floatVal3: Float?, var floatVal4: Float?): Comparable<CustomObject>{
        override fun compareTo(other: CustomObject) = (floatVal1 - other.floatVal1).toInt()
    }

That specific question from duplicate post does not show me how to get max/min value based on Float. That's the problem. If I want to modify Comparator it accepts only Int. And i cant use that stream feature because my app is for API 23+ not 24+

like image 682
martin1337 Avatar asked Sep 23 '18 12:09

martin1337


Video Answer


3 Answers

val maxObj: Object? = arrayList.maxByOrNull { it.floatVal1 }
val minObj: Object? = arrayList.minByOrNull { it.floatVal2 }

maxBy, minBy are deprecated since Kotlin 1.4

like image 52
Akila Wasala Avatar answered Nov 05 '22 21:11

Akila Wasala


I think you're looking for minBy and maxBy:

 val minObject: CustomObject? = arrayList.minBy { it.floatVal1 }
 val maxObject: CustomObject? = arrayList.maxBy { it.floatVal1 }
like image 40
zsmb13 Avatar answered Nov 05 '22 19:11

zsmb13


This return non-null types:

list.maxOf { it.value }
list.minOf { it.value }
like image 34
Falchio Avatar answered Nov 05 '22 21:11

Falchio