简体   繁体   English

使用流来查找Max

[英]Using streams to find Max

Is the following the recommended way to attempt finding Max with streams? 以下是尝试使用流来寻找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);

It results in a compilation error - what does this mean? 它导致编译错误 - 这是什么意思?

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

You can use the method Integer.min in reduce which returns OptionalInt , can be used to get Int (make sure the boundary checks) 你可以在reduce中使用Integer.min方法返回OptionalInt ,可以用来获取Int (确保边界检查)

using IntStream 使用IntStream

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

using IntSummaryStatistics [if you are interested in statistics, like min, max, avg] 使用IntSummaryStatistics [如果你对统计感兴趣,比如min,max,avg]

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

reduce function reduce功能

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

First, you might shorten your emps initialization with Arrays.asList(T...) like 首先,您可以使用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));

Next, you can use OptionalInt.orElseThrow(Supplier<X>) which will get the max value from the List or throw a RuntimeException 接下来,您可以使用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);

Finally, you could also reason that no one would accept a negative salary, and use orElse(int) like 最后,你也可以有理由相信没有人会接受负薪,并使用orElse(int)

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

Answering to your question the problem is that reduce method is going to return an OptionalInt so you need to call the .getAsInt() method if you want to have the Integer value. 回答你的问题,问题是reduce方法将返回一个OptionalInt因此如果你想拥有Integer值,你需要调用.getAsInt()方法。

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

In case there is no maximum on the list you will get a NoSuchElementException that you need to deal with. 如果列表中没有最大值,您将获得需要处理的NoSuchElementException

There is already a max method in IntStream . IntStream已经有一个max方法。 You don't have to reinvent the wheel: 你不必重新发明轮子:

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

max returns OptionalInt instead of Integer because there can be no elements in the list. max返回OptionalInt而不是Integer因为列表中没有元素。 You can use OptionalInt methods to extract the value from it: 您可以使用OptionalInt方法从中提取值:

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

Or: 要么:

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

Or: 要么:

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

The latter one may throw an exception, so be careful. 后者可能会抛出异常,所以要小心。

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

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