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?

ADM
  • 20,406
  • 11
  • 52
  • 83
LAffair
  • 1,968
  • 5
  • 31
  • 60

2 Answers2

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.

Alan Raso
  • 263
  • 2
  • 9
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);

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51