简体   繁体   English

Java 流可以找到除 Max 之外的所有内容

[英]Java streams to find all apart from Max

I am still learning java streams and could not figure out a solution for my problem.我仍在学习 java 流,无法找到解决问题的方法。

scenario:设想:

I have a list of objects which each object has an identifier called stageNo.我有一个对象列表,每个对象都有一个名为 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.所以基本上我要做的是根据 stageNo 过滤掉最大对象并将方法设置为特定值。

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.这将导致具有最大 stageNo 的对象,并将 flag 方法相应地设置为 1。这可以正常工作,没有问题。

now I am trying to find all object that meets filtering but instead of max, find everything apart from max and setFlag(0) instead.现在我试图找到所有满足过滤条件的对象,而不是 max,而是找到除了max 和 setFlag(0) 之外的所有对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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