Java 8 流“ifPresent”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38688119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:41:00  来源:igfitidea点击:

Java 8 streams "ifPresent"

javalambdajava-8java-stream

提问by Stefan B

I am trying to learn about streams and encountered a problem: I want to get the minimal value of a list and assign it to an int variable. For that I did the following:

我正在尝试了解流并遇到一个问题:我想获取列表的最小值并将其分配给一个 int 变量。为此,我做了以下工作:

List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    int smallest = list.stream().min(Integer::compareTo).get();
    System.out.println(smallest);

This works well and i get 1as a result. The issue is that the IDE gives the warning that Optional.getis called before checking for .isPresent. To fix that i used the slightly different ifPresentmethod and tried the following:

这很有效,我得到1了结果。问题是 IDEOptional.get在检查.isPresent. 为了解决这个问题,我使用了稍微不同的ifPresent方法并尝试了以下方法:

int smallest = list.stream().min(Integer::compareTo).ifPresent(integer -> integer);

Unfortunately this doesn't work since I get the warning: Bad return type in Lambda, Integer cannot be converted to void.My question finally is: How can I assign the min value to the int smallestvariable WITH checking ifPresent?

不幸的是,这不起作用,因为我收到警告:Bad return type in Lambda, Integer cannot be converted to void.我的问题最后是:如何通过int smallest检查 ifPresent将最小值分配给变量?

采纳答案by Nazarii Bardiuk

Stream#minreturn Optionalof result because in general stream can be empty so there can be no minimal value.

Stream#minOptional结果的返回,因为通常流可以为空,因此没有最小值。

 Optional<Integer> minimal = list.stream().min(Integer::compareTo);

To get value from Optional you need to have some fallback value

要从 Optional 获得价值,您需要有一些后备价值

Integer absent = Integer.MIN_VALUE;

The easiest would be to use orElse

最简单的方法是使用 orElse

Integer smallest = minimal.orElse(absent);

Little bit longer would be isPresent

长一点会 isPresent

Integer smallest = minimal.isPresent() ? minimal.get() : absent;

回答by duffymo

Here's how I'd do it:

这是我的做法:

package lambdas;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Michael
 * Creation date 7/31/2016.
 * @link https://stackoverflow.com/questions/38688119/java-8-streams-ifpresent
 */
public class MinimumExample {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        int smallest = list.stream().min(Integer::compareTo).orElse(Integer.MIN_VALUE);
        System.out.println(smallest);
    }
}

回答by Andrew Tobilko

The ifPresentmethod takes Consumer<? super T>as a parameter. Simply speaking, it should be an action without returnstatement. You could print the value if it's present, like

ifPresent方法Consumer<? super T>作为参数。简单的说,应该是一个没有return声明的动作。如果存在,您可以打印该值,例如

[...].ifPresent(System.out::print);

But it is not what about IDEA says. I think, you simply need to save an Option<Integer>instance and then check it by isPresent:

但这不是IDEA所说的。我认为,您只需要保存一个Option<Integer>实例,然后通过isPresent以下方式检查它:

Optional<Integer> o = list.stream().min(Integer::compareTo);
if (o.isPresent()) {
    smallest = o.get();
}

Of course, there are more convenient ways with orElse:

当然,还有更方便的方法orElse

smallest = o.orElse(Integer.MIN_VALUE);

or with the ternary operator:

或使用三元运算符:

smallest = o.isPresent() ? o.get() : Integer.MIN_VALUE;