[英]Get Minimum object based on some fields from a List of objects
I'm new in Android development and I'm trying to find the best way to get the minimum object from the object list based on 3 fields. 我是Android开发的新手,我正在尝试找到基于3个字段从对象列表中获取最小对象的最佳方法。 I have an object list, each object having 4 fields: Name
, State
(int value), LSeconds
(int value) and USeconds
(int value). 我有一个对象列表,每个对象有4个字段: Name
, State
(int value), LSeconds
(int value)和USeconds
(int value)。 I want to get the minimum object based first by State
(minimum State value) and if two or more objects have the same minimum state to check the LSeconds
value for the find objects and if those are also the same to check by USeconds
and in the end to return the first one if there are more than one object with the same minimum State
, minimum LSeconds
and minimum USeconds
. 我希望首先通过State
获取最小对象(最小状态值),如果两个或多个对象具有相同的最小状态,则检查查找对象的LSeconds
值,如果这些也是相同的, USeconds
检查并且在如果有多个具有相同最小State
对象,最小LSeconds
和最小USeconds
,则返回第一个。 Is there a function that can do this automatically or do I need to do it by using the for
? 是否有一个可以自动执行此操作的功能,或者我是否需要通过使用for
来执行此操作?
Java doesn't have this sort function with objects you're looking for. Java没有与您正在寻找的对象具有此排序功能。 If you use StreamSupport Java library though, there's a method you can use, something like this: 如果您使用StreamSupport Java库,可以使用一种方法,如下所示:
List<YourObject> result = list.stream().sorted((ob1, ob2)-> ob1.getState().
compareTo(ob2.getState())).
collect(Collectors.toList());
You can work with this lambda to apply the logic you're looking for (check State
first, then LSeconds
, etc..) 您可以使用此lambda来应用您正在寻找的逻辑(首先检查State
,然后检查LSeconds
等。)
PS: you can do this easily with Kotlin, like in this question PS:你可以像Kotlin一样轻松地做到这一点,就像这个问题一样
EDIT : Actually, you can with Java 8, sorry. 编辑 :其实,你可以用Java 8,抱歉。 Check @mạnh-quyết-nguyễn answer . 检查@mạnh-quyết-nguyễn的 答案 。
In java 8 you can use Comparator : 在java 8中,您可以使用Comparator :
Comparator<YourObject> comparator = Comparator.comparing(YourObject::getState)
.thenComparing(YourObject::getLSeconds)
.thenComparing(YourObject::getUSeconds);
Then you can sort your list: Collections.sort(yourList, comparator);
然后你可以对列表进行排序: Collections.sort(yourList, comparator);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.