Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression and Optional how to return String value

I'd like to get an Optional value, I have something like this:

Optional<String> value =

Optional.ofNullable(MyObject.getPeople())
    .ifPresent(people -> people                                                                    
        .stream()                                                                    
        .filter(person -> person.getName().equals("test1"))
        .findFirst()
        .map(person -> person.getId()));

person.getId() should return a string, I tried this but it didn't work, getting incompatible types: void cannot be converted to java.util.Optional

Optional<String> value =

Optional.ofNullable(MyObject.getPeople())
    .ifPresent(people -> people                                                                    
        .stream()                                                                    
        .filter(person -> person.getName().equals("test1"))
        .findFirst()
        .map(person -> person.getId()))
        .orElse(null);

Any idea? Thanks

like image 307
David Avatar asked Nov 07 '18 14:11

David


2 Answers

Optional.ifPresent takes a Consumer - so you cannot return anything from it. Use Optional.map.

Optional.ofNullable(MyObject.getPeople())
    .map(people -> people                                                                    
        .stream()                                                                    
        .filter(person -> person.getName().equals("test1"))
        .findFirst()
        .map(person -> person.getId()))
    .orElse(null);

A better one would be to use flatmap and not return a null at the end (It is not recommended to assign null to an Optional variable)

Optional.ofNullable(MyObject.getPeople())
    .flatmap(people -> people                                                                    
        .stream()                                                                    
        .filter(person -> person.getName().equals("test1"))
        .findFirst()
        .map(person -> person.getId()));

Note: Your first statement is also a bit weird. If MyObject.getPeople returns a collection, then there is no need to wrap it with an Optional (unless the return value could be null - but again, it is recommended not to return null when the return type is a Collection).

like image 176
user7 Avatar answered Nov 14 '22 23:11

user7


Assuming people is a Collection, the first use of Optional is not needed. You may do it like so,

Optional<String> value = MyObject.getPeople().stream()
    .filter(person -> person.getName().equals("test1"))
    .findFirst().map(person -> person.getId());

If there exists a value it will return it, otherwise it will return an empty Optional.

like image 42
Ravindra Ranwala Avatar answered Nov 14 '22 21:11

Ravindra Ranwala