简体   繁体   中英

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.

Question : I have some object A, I want to filter it based on a numerical value that it holds, say, an integer. I want to find the object with the highest value and then return that 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.

There's not necessarily a need for streams, you could also use Collections.max with a custom comparator:

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).

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

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