繁体   English   中英

使用流来查找Max

[英]Using streams to find Max

以下是尝试使用流来寻找Max的推荐方法吗?

List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b));
System.out.println("Max " + maxSal);

它导致编译错误 - 这是什么意思?

error: incompatible types: OptionalInt cannot be
nverted to Integer
                  Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).
uce((a,b)->Math.max(a, b));

你可以在reduce中使用Integer.min方法返回OptionalInt ,可以用来获取Int (确保边界检查)

使用IntStream

int max1 = emps.stream().mapToInt(Employee::getSalary).max().getAsInt();

使用IntSummaryStatistics [如果你对统计感兴趣,比如min,max,avg]

IntSummaryStatistics stats = emps.stream().mapToInt(Employee::getSalary).summaryStatistics();
int max2 = stats.getMax();

reduce功能

int max3 = emps.stream().mapToInt(Employee::getSalary).reduce(Integer::min).getAsInt();

首先,您可以使用Arrays.asList(T...)缩短您的emps初始化

List<Employee> emps = Arrays.asList(new Employee("Roy1", 32), 
        new Employee("Roy2", 12), new Employee("Roy3", 22),
        new Employee("Roy4", 42), new Employee("Roy5", 52));

接下来,您可以使用OptionalInt.orElseThrow(Supplier<X>) ,它将从List获取max 抛出RuntimeException

int maxSal = emps.stream().mapToInt(Employee::getSalary).max()
        .orElseThrow(() -> new RuntimeException("No Such Element"));
System.out.println("Max " + maxSal);

最后,你也可以有理由相信没有人会接受负薪,并使用orElse(int)

int maxSal = emps.stream().mapToInt(Employee::getSalary).max().orElse(-1);
System.out.println("Max " + maxSal);

回答你的问题,问题是reduce方法将返回一个OptionalInt因此如果你想拥有Integer值,你需要调用.getAsInt()方法。

    Integer maxSal = emps.stream().mapToInt(e -> e.getSalary())
         .reduce((a,b)->Math.max(a, b)).getAsInt();

如果列表中没有最大值,您将获得需要处理的NoSuchElementException

IntStream已经有一个max方法。 你不必重新发明轮子:

OptionalInt maxSal = emps.stream().mapToInt(Employee::getSalary).max();
System.out.println("Max " + maxSal);

max返回OptionalInt而不是Integer因为列表中没有元素。 您可以使用OptionalInt方法从中提取值:

maxSal.ifPresent(System.out::println);

要么:

System.out.println(maxSal.orElse(0));

要么:

System.out.println(maxSal.getAsInt());

后者可能会抛出异常,所以要小心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM