简体   繁体   English

Java 8 Stream从过滤结果中获取对象

[英]Java 8 Stream get object from filter result

Note: I don't know if I titled this correctly, so please feel free to alter it to something more appropriate, I'm quite new to the terminology of Java 8. 注意:我不知道我是否正确标题,所以请随意将其更改为更合适的东西,我对Java 8的术语很新。

Question : I have some object A, I want to filter it based on a numerical value that it holds, say, an integer. 问题 :我有一些对象A,我想基于它所拥有的数值来过滤它,比如一个整数。 I want to find the object with the highest value and then return that Object. 我想找到具有最高值的对象,然后返回该Object。 How is this done using streams? 如何使用流完成?

public SomeObject getObjectWithHighestValue()
{
    int max = Integer.MIN_VALUE;
    SomeObject maxObj = null;

    for(SomeObject someObj : someList)
    {
        if(someObj.getValue() > max)
        {
            max = someObj.getValue();
            maxObj = someObj;
        }
    }

    return maxObj;
}

Above I have included a java 7 way of doing roughly what I want. 上面我已经包含了一个java 7的方式来做我想要的大致。

There's not necessarily a need for streams, you could also use Collections.max with a custom comparator: 不一定需要流,您也可以使用Collections.max和自定义比较器:

import static java.util.Collections.max;
import static java.util.Comparator.comparing;

...

SomeObject o = max(someList, comparing(SomeObject::getValue));

The advantages with the stream approach is that you can parallelize the task if needed, and you get back an empty Optional if the list is empty (whereas it would throw an exception with an empty list using Collections.max , but you can check the size before). 流方法的优点是,如果需要,您可以并行化任务,如果列表为空,则返回空的可选项(而使用Collections.max使用空列表抛出异常,但您可以检查大小之前)。

return list.stream()
           .max(Comparator.comparing(SomeObject::getValue))
           .orElse(null);
SomeObject maxObject = someList.stream().max(Comparator.comparing(SomeObject::getValue).get();

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

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