我有一个类,其中包含一个最小对象值的模型,如下所示
public class ModelObject implements Serializable {
private Long min;
//getters and setters
我如图所示在控制器中创建了此模型的列表
List<ModelObject > modelObject = new ArrayList<>();
for(EggsHatched hatched: eggsList) {
EggsHatched minByEgg = eggsList
.stream()
.min(minByEgg.getHatched()) //here throws error of The method min(Comparator<? super EggsHatched>) in the type Stream<EggsHatched> is not applicable for the arguments (Long)
.orElseThrow(NoSuchElementException::new);
modelObject.setMin(minByEgg);// I cannot do this here because the above gives me error
}
请问我如何从eggsList中获取最小值
答案 0 :(得分:1)
minByEgg.getHatched()
不是Comparator<EggsHatched>
,因此您不能将其传递给min
。
使用:
EggsHatched minByEgg = eggsList
.stream()
.min(Comparator.comparing(EggsHatched::getHatched))
.orElseThrow(NoSuchElementException::new);
P.S。,目前还不清楚为什么将流管道放入循环访问eggsList
的循环中。使用Stream
时,不需要循环。
modelObject.setMin(minByEgg)
也没有意义,因为modelObject
是List
,没有setMin
方法。
如果要计算getHatched()
中所有元素的List
值(例如最小值,最大值和平均值)的数值属性,则可以映射到LongStream
和致电summaryStatistics
:
LongSummaryStatistics stats = eggsList
.stream()
.mapToLong(EggsHatched::getHatched)
.summaryStatistics();