3

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. I have an object list, each object having 4 fields: Name, State (int value), LSeconds (int value) and 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. Is there a function that can do this automatically or do I need to do it by using the for?

1

2 Answers 2

4

Java doesn't have this sort function with objects you're looking for. If you use StreamSupport Java library though, there's a method you can use, something like this:

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..)

PS: you can do this easily with Kotlin, like in this question

EDIT: Actually, you can with Java 8, sorry. Check @mạnh-quyết-nguyễn answer.

Sign up to request clarification or add additional context in comments.

2 Comments

You can do it with Java.
Thanks for the heads up, linked your answer on a edit.
3

In java 8 you can use Comparator:

Comparator<YourObject> comparator = Comparator.comparing(YourObject::getState)
                         .thenComparing(YourObject::getLSeconds)
                         .thenComparing(YourObject::getUSeconds);

Then you can sort your list: Collections.sort(yourList, comparator);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.