Get the smallest object based on certain fields in the object list
I’m new to Android development and I’m trying to find the best way to get the fewest objects from a list of objects based on 3 fields.
I have a list of objects with 4 fields each:
State (int value), LSeconds (int value), and
I want to get the smallest object based on
State (minimum state value) first, check the LSeconds value of the lookup object if two or more objects have the same minimum state, if these are also the same, then pass
the USeconds check, if there are multiple objects with the same minimum
state, and finally return the first, minimum
LSeconds and minimal
USeconds. Is there a function that can do this automatically, or do I need to use
for to do this?
Java does not have the ability to sort the object you are looking for. If you use StreamSupport is a Java library, but you can use one method as follows:
List<YourObject> result = list.stream().sorted((ob1, ob2)-> ob1.getState(). compareTo(ob2.getState())). collect(Collectors.toList());
You can use this lambda to apply the logic you are looking for (check
State first, then
LSeconds, and so on).
PS: You can easily do this with Kotlin, like this question