如何使用 Java 8 从对象列表中获取最小值和最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31083405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get minimum and maximum value from List of Objects using Java 8
提问by Vishwa
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.
和一个List<Test> testList
充满Test
元素的列表。
How can I get minimum and maximum value of age
using Java 8?
如何获得age
使用 Java 8 的最小值和最大值?
回答by Pshemo
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.
为了简化事情,您可能应该使用您的年龄Integer
或int
代替 Sting,但由于您的问题是关于String age
此答案的,因此将基于String
类型。
Assuming that String age
holds String representing value in integer range you could simply map it to IntStream
and use its IntSummaryStatistics
like
假设String age
持有字符串代表整数的范围值,你可以简单地把它映射到IntStream
和使用它的IntSummaryStatistics
像
IntSummaryStatistics summaryStatistics = testList.stream()
.map(Test::getAge)
.mapToInt(Integer::parseInt)
.summaryStatistics();
int max = summaryStatistics.getMax();
int min = summaryStatistics.getMin();
回答by lasclocker
max age
:
最大值age
:
testList.stream()
.mapToInt(Test::getAge)
.max();
min age
:
分钟age
:
testList.stream()
.mapToInt(Test::getAge)
.min();