2015-06-26 36 views
4

我有喜欢类摆脱对象列表最小值和最大值:如何使用Java 8

public class Test { 
    private String Fname; 
    private String Lname; 
    private String Age; 
    // getters, setters, constructor, toString, equals, hashCode, and so on 
} 

和充满Test元素,如List<Test> testList列表。

如何使用Java 8获得最小值和最大值age

+1

排序列表;) – MadProgrammer

+1

我恨听起来像一个破纪录,但是......'你有什么尝试?向我们展示一些代码和一个特定的错误或问题。' – Jashaszun

+1

既然你指定了,你想使用Java 8,请看['Streams'](https://docs.oracle.com/javase/8/docs /api/java/util/stream/Stream.html)。你应该能够自己找出其余的问题。 – Turing85

回答

17

为了简化事情你应该让你的Integer年龄或int,而不是螫人,但因为你的问题是关于String age这个答案将根据String类型。


假设String age持有字符串表示整数值范围,你可以简单地把它映射到IntStream并使用其IntSummaryStatistics

IntSummaryStatistics summaryStatistics = testList.stream() 
     .map(Test::getAge) 
     .mapToInt(Integer::parseInt) 
     .summaryStatistics(); 

int max = summaryStatistics.getMax(); 
int min = summaryStatistics.getMin(); 
+1

不需要双图;只是mapToInt(Test :: getAge),拆箱将为您完成。 –

+2

@BrianGoetz不完全。注意'getAge'返回'String'而不是'int'。 – Pshemo

+3

谁写字段中存储数字的对象?啧。 :) –