如何根据其对象属性值从 ArrayList 获取最小值/最大值?

编程入门 行业动态 更新时间:2024-10-22 17:33:03
本文介绍了如何根据其对象属性值从 ArrayList 获取最小值/最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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+

推荐答案

我想你正在寻找 minBymaxBy:

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:关键词]

本文发布于:2023-04-16 10:43:14,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最大值   属性   最小值   对象   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!