你好。任务是找到列表中的最大元素。请告诉我为什么以下代码不能正常工作:
import java.util.*;
public class Main {
public static void main(String[] args){
List<Integer> list = new ArrayList<>();
list.add(847);
list.add(271);
list.add(879);
System.out.println(maxElem(list));
}
public static Integer maxElem(List<Integer> list){
Integer max = list.stream()
.max(Math::max)
.get();
return max;
}
}
结果不是预期的 879,而是 847。为什么?
更新。评论详细解释了为什么代码不能正常工作。我不会重复自己,我只会给出正确代码的不同版本。
Integer max = list.stream().reduce(Integer::max).get();
Integer max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
Integer max = list.stream().mapToInt(Integer::intValue).max().getAsInt();
Integer max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();
Integer max = list.stream().max(Comparator.naturalOrder()).get();
Integer max = list.stream().max(Integer::compare).get();
Integer max = list.stream().max((a, b) -> {
if (a > b) return 1;
else if (a < b) return -1;
else return 0;
}).get();
Stream.max方法接受
Comparator. 尝试传递它:现在你正在传递给
max方法Math.max。Java 将此方法视为Comparator的实现,并尝试使用该方法确定Math.max最大值Comparator.compare。因为Math.max不是比较操作的有效实现,将返回不可预知的结果。Math::maxreturns(a >= b) ? a : b,而 stream.max() 采用Comparator,其工作方式不同: Comparator “需要”三个基值:小于 -1,等于 0,大于 1,而 Math::max 方法不需要返回那个。因此,您需要使用自己的 Comparator 或使用 Integer 类中现成的 Comparator:
Integer.compare试试吧,它对我有用
一切似乎都很简单: