Lucas Pires Lucas Pires - 4 months ago 19
Java Question

How to return orElseThrow in a same condition with ifPresent using Java 8?

I have a Java 8 code below using ifPresent, I want in the same condition to use orElseThrow

chatSessionStore.get(group)
Already returns a Optional object.

@Override
public void forwardMessageGroup(String group, ChatMessage message) {

chatSessionStore.get(group).ifPresent(chatProxy -> chatProxy.sendMessage(message));

}


Any tips?

Answer

I think what you want is simply:

chatSessionStore.get(group).orElseThrow(
      () -> new RuntimeException("No group")
).sendMessage(message);
Comments