简体   繁体   中英

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?

I think what you want is simply:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM