Suppose to have a class Obj
class Obj{
int field;
}
and that you have a list of Obj
instances, i.e. List<Obj> lst
.
Now, how can I find in Java8 the minimum value of the int fields field
from the objects in list lst
?
toList()); T min = sorted. get(0); T max = sorted. get(sorted. size() - 1);
ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
list.stream().min((o1,o2) -> Integer.compare(o1.field,o2.field))
Additional better solution from the comments by Brian Goetz
list.stream().min(Comparator.comparingInt(Obj::getField))
You can also do
int min = list.stream().mapToInt(Obj::getField).min();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With