Java Optional if object is not null - returns the method result, if null - returns default value

前端 未结 5 1725
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 21:26

Is it possible to transform this code to a Java 8 Optional one-line expression?

long lastPollTime;
if (object != null) {
    lastPollTime = object.getTime();
         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-23 21:54

    you can do like below with java 8

    long lastPollTime=Optional.ofNullable(object).isPresent()?object.getTime():0;
    

    or without using java8 like this

     long lastPollTime = object != null ?object.getTime():0;
    

提交回复
热议问题