代码之家  ›  专栏  ›  技术社区  ›  vtokmak

将旧式if用法转换为可选.ifPresent()时出现问题

  •  2
  • vtokmak  · 技术社区  · 8 年前

    Optional.ifPresent . 这是以前版本的代码。

    State state = State.OK;
    final Optional<Person> checkExistingPerson = checkIt();
    
    if(checkExistingPerson.isPresent()) {
        Person person = checkExistingPerson.get();
    
        if("blah".equals(person.getName())) {
            state = State.DUPLICATE;
        } else {
            state = State.RESTORED;
        }
    
        return Member(person.getId(), state);
    }
    
    return Member(null, state);
    

    这里是 使用

    State state = State.OK;
    final Optional<Person> checkExistingPerson = checkIt();
    
    checkExistingPerson.ifPresent(person -> {
    
        if("blah".equals(person.getName())) {
            state = State.DUPLICATE;
        } else {
            state = State.NEW;
        }
    
        return Member(person.getId(), state);
    });
    
    return Member(null, state);
    

    enter image description here

    最好的使用方法是什么 Optional

    4 回复  |  直到 8 年前
        1
  •  3
  •   Loris Securo    8 年前
    1. final
    2. ifPresent 接受 Consumer 所以它没有返回值,所以不能使用 return Member(person.getId(), state); (还要记住你在一个lambda里面,所以 return

    map 而是接受 Function 它有一个返回值,所以你可以用它来代替 如果存在 .

    这就是如何通过移动 state 在lambda内部使用 和 orElseGet :

    return checkExistingPerson.map(person -> {
        State state;
    
        if("blah".equals(person.getName())) {
            state = State.DUPLICATE;
        } else {
            state = State.NEW;
        }
    
        return Member(person.getId(), state);
    })
    .orElseGet(() -> Member(null, State.OK));
    
        2
  •  3
  •   fps    8 年前

    不能在lambda表达式中更改局部变量的值。除此之外, ifPresent 无法返回值,因为其返回类型为 void .

    Optional.map Optional 如果存在:

    return checkExistingPerson
        .map(person -> new Member(
                person.getId(), 
                "blah".equals(person.getName()) ? State.DUPLICATE : State.RESTORED))
        .orElse(new Member(null, State.OK));
    
        3
  •  1
  •   TheOni    8 年前

    在内部方法中,如果外部变量未定义为final,则不能引用外部变量,可以这样更改方法:

    final Optional<Person> checkExistingPerson = checkIt();
    
    checkExistingPerson.ifPresent(person -> {
        State state;
        if("blah".equals(person.getName())) {
            state = State.DUPLICATE;
        } else {
            state = State.NEW;
        }
    
        return Member(person.getId(), state);
    });
    
    return Member(null, State.OK); 
    
        4
  •  1
  •   Ryuzaki L    8 年前

    here ,您还可以在lambda表达式中声明变量,以及有关问题的主题 ifPresent 将采取 Consumer 作为没有返回类型的参数,使用 map 那要花多少时间 Function