Avoid NoSuchElementException with Stream

前端 未结 3 1057
傲寒
傲寒 2020-12-08 13:09

I have the following Stream:

Stream stream = stream();

T result = stream.filter(t -> {
    double x = getX(t);
    double y = getY(         


        
3条回答
  •  北海茫月
    2020-12-08 13:55

    Stream#findFirst() returns an Optional which exists specifically so that you don't need to operate on null values.

    A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

    Otherwise, Optional#get() throws a NoSuchElementException.

    If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.

    An Optional will never expose its value if it is null.

    If you really have to, just check isPresent() and return null yourself.

    Stream stream = stream();
    
    Optional result = stream.filter(t -> {
        double x = getX(t);
        double y = getY(t);
        return (x == tx && y == ty);
    }).findFirst();
    
    if (result.isPresent()) 
        return result.get();
    return null;
    

提交回复
热议问题