fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Optional<UserDTO> user = Optional.of(new UserDTO(null));
  13. user.ifPresent(u -> {
  14. u.getGroup().orElseThrow(() -> new EntityNotFoundException("Grupo não encontrado"));
  15. });
  16. }
  17.  
  18. public static class EntityNotFoundException extends RuntimeException {
  19. public EntityNotFoundException(String message) {
  20. super(message);
  21. }
  22. }
  23.  
  24. public static class UserDTO {
  25. private GroupEntity group;
  26.  
  27. public UserDTO(GroupEntity group) {
  28. this.group = group;
  29. }
  30.  
  31. public Optional<GroupEntity> getGroup() {
  32. return Optional.ofNullable(this.group);
  33. }
  34. }
  35.  
  36. public static class GroupEntity {
  37.  
  38. }
  39. }
Runtime error #stdin #stdout #stderr 0.19s 33340KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Exception in thread "main" Ideone$EntityNotFoundException: Grupo não encontrado
	at Ideone.lambda$null$0(Main.java:14)
	at java.util.Optional.orElseThrow(Optional.java:290)
	at Ideone.lambda$main$1(Main.java:14)
	at java.util.Optional.ifPresent(Optional.java:159)
	at Ideone.main(Main.java:13)