简体   繁体   中英

Java streams to find all apart from Max

I am still learning java streams and could not figure out a solution for my problem.

scenario:

I have a list of objects which each object has an identifier called stageNo.

So basically what I am trying to do is filter out the max objects according to stageNo and set a method 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 all object that meets filtering but instead of max, find everything apart from max and setFlag(0) instead.

I am not entirely sure on the way to do so, tried looking for solutions, however could not find one.

Thanks

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;
         });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM