问题描述
限时送ChatGPT账号..我想要实现的是从ArrayList
中获取对象的最小/最大属性值.例如,如果 Object
具有属性 weight
(float),我想要列表中最重的对象.
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.
我尝试实现 Comparable 以获得最大/最小值,但是由于某种原因,这返回相同的 min 值和相同的 max 值.(我不知道它是否适用于浮动)
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()
}
重复帖子中的那个特定问题没有告诉我如何根据浮点数获得最大值/最小值.那就是问题所在.如果我想修改 Comparator 它只接受 Int.而且我无法使用该流功能,因为我的应用程序适用于 API 23+ 而不是 24+
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+
推荐答案
我想你正在寻找 minBy
和 maxBy
:
I think you're looking for minBy
and maxBy
:
val minObject: CustomObject? = arrayList.minBy { it.floatVal1 }
val maxObject: CustomObject? = arrayList.maxBy { it.floatVal1 }
这篇关于如何根据其对象属性值从 ArrayList 获取最小值/最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论