Reputation: 23
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.
Upvotes: 2
Views: 1205
Reputation: 93842
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).
Upvotes: 4
Reputation: 3681
SomeObject maxObject = someList.stream().max(Comparator.comparing(SomeObject::getValue).get();
Upvotes: 1
Reputation: 691685
return list.stream()
.max(Comparator.comparing(SomeObject::getValue))
.orElse(null);
Upvotes: 3