簡體   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