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
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With