Assign value of Optional to a variable if present

前端 未结 5 2402
栀梦
栀梦 2021-02-19 02:13

Hi I am using Java Optional. I saw that the Optional has a method ifPresent.

Instead of doing something like:

Optional object = someMeth         


        
相关标签:
5条回答
  • 2021-02-19 02:43

    Optional l = stream.filter..... // java 8 stream condition

            if(l!=null) {
                ObjectType loc = l.get();
                Map.put(loc, null);
            }
    
    0 讨论(0)
  • 2021-02-19 02:45

    Quite late but I did following:

    String myValue = object.map(x->x.getValue()).orElse("");
                               //or null. Whatever you want to return.
    
    0 讨论(0)
  • 2021-02-19 02:46

    You could use #orElse or orElseThrow to improve the readbility of your code.

    Optional<MyObject> object = someMethod();
    String myValue = object.orElse(new MyObject()).getValue();
    

    Optional<MyObject> object = someMethod();
    String myValue = object.orElseThrow(RuntimeException::new).getValue();
    
    0 讨论(0)
  • 2021-02-19 02:46

    .findFirst() returns a Optional<MyType>, but if we add .orElse(null) it returns the get of the optional if isPresent(), that is (MyType), or otherwise a NULL

    MyType s = newList.stream().filter(d -> d.num == 0).findFirst().orElse(null);
    
    0 讨论(0)
  • 2021-02-19 02:50

    You need to do two things:

    1. Turn your Optional<MyObject> into an Optional<String>, which has a value iff the original Optional had a value. You can do this using map: object.map(MyObject::toString) (or whatever other method/function you want to use).
    2. Get the String value of of your Optional<String>, or else return a default if the Optional doesn't have a value. For that, you can use orElse

    Combining these:

    String myValue = object.map(MyObject::toString).orElse(null);
    
    0 讨论(0)
提交回复
热议问题