I am still learning Java streams and could not figure out a solution for my problem.
I have a list of objects which each object has an identifier called stageNo
.
I am trying to filter out the max objects according to stageNo
and call a method to set a specific value.
code:
Object currentObject = new Object();
List<Object> objects = new ArrayList<>();
objects
.stream()
.filter(object -> object.stageNoCalculate == currentObject.getStageNo)
.filter(object -> object.executionDate != null)
.max(Comparator.comparing(Object::getStageNo)
.map(object -> {
object.setFlag(1);
return object;
}).get();
This will result with the object that has the max stageNo and will set the flag method accordingly to 1. This works properly with no issues.
Now I am trying to find each other object that meets the same filtering criteria except the max:
find everything apart from max and call setFlag(0)
instead.
I am not entirely sure how to do so. I've tried looking for solutions, but I could not find one.
You could sort your stream from max to min, and skip the first element.
objects
.stream()
.filter(object -> object.stageNoCalculate == currentObject.getStageNo)
.filter(object -> object.executionDate != null)
.sorted(Comparator.comparing(Object::getStageNo).reversed())
.skip(1) //Skip the first element, which is the max
.forEach(object -> {
object.setFlag(0);
return object;
});