I have class like:
public class Test {
private String Fname;
private String Lname;
private String Age;
// getters, setters, constructor, toString, equals, hashCode, and so on
}
and a list like List<Test> testList
filled with Test
elements.
How can I get minimum and maximum value of age
using Java 8?
2. Using Stream. max() method. The idea is to convert the list into a Stream and call Stream#max() that accepts a Comparator to compare items in the stream against each other to find the maximum element, and returns an Optional containing the maximum element in the stream according to the provided Comparator .
To simplify things you should probably make your age Integer
or int
instead of Sting, but since your question is about String age
this answer will be based on String
type.
Assuming that String age
holds String representing value in integer range you could simply map it to IntStream
and use its IntSummaryStatistics
like
IntSummaryStatistics summaryStatistics = testList.stream()
.map(Test::getAge)
.mapToInt(Integer::parseInt)
.summaryStatistics();
int max = summaryStatistics.getMax();
int min = summaryStatistics.getMin();
max age
:
testList.stream()
.mapToInt(Test::getAge)
.max();
min age
:
testList.stream()
.mapToInt(Test::getAge)
.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