数据对象列表中的最小值返回方法min(Comparator <!-?super EggsHatched->)错误

时间:2018-08-26 07:50:14

标签: java arraylist

我有一个类,其中包含一个最小对象值的模型,如下所示

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中获取最小值

1 个答案:

答案 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)也没有意义,因为modelObjectList,没有setMin方法。

如果要计算getHatched()中所有元素的List值(例如最小值,最大值和平均值)的数值属性,则可以映射到LongStream和致电summaryStatistics

LongSummaryStatistics stats = eggsList
                  .stream()
                  .mapToLong(EggsHatched::getHatched)
                  .summaryStatistics();