Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a method reference inside an Optional.map()

I have a Optional.

Optional<AssetEvent> latestEvent = ...

I want to a add a field from inside the Event to a List if Present.

latestEvent.map(event -> event.getTimestamp()).ifPresent(latestList::add);

My IDE (Intelij) shows me "Lambda can be replaced with method reference" on event.getTimestamp()

refactoring to

latestEvent.map(this::getTimestamp).ifPresent(latestList::add);

gives me an Error because this will refer to the surrounding Object in what the code is executed. How can I refer to the method of the Object inside the Optional latestEvent

like image 492
DIBits Avatar asked May 12 '26 12:05

DIBits


1 Answers

Use the class name. For example:

latestEvent.map(AssetEvent::getTimestamp).ifPresent(latestList::add);

Assuming AssetEvent is the name of the class having the getTimestamp method.

like image 136
Eran Avatar answered May 14 '26 03:05

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!