Skip to content

Instantly share code, notes, and snippets.

@codinko
Last active November 19, 2018 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinko/7442277d712a4da28ecff5b9ca60bb76 to your computer and use it in GitHub Desktop.
Save codinko/7442277d712a4da28ecff5b9ca60bb76 to your computer and use it in GitHub Desktop.
java.util.Optional.map code snippet-1
// Get all notes by userId
java.util.Optional;
java.util.Optional.map()
java.util.Optional class
// A container object which may or may not contain a non-null value.
// If a value is present, {@code isPresent()} will return {@code true} and
// {@code get()} will return the value.
// Approach-1
Optional<NoteUser> noteUser = noteRepository.findById(userId);
if (noteUser.isPresent()) {
List<Note> notes = noteUser.get().getNotes();
}
return notes;
// Approach-2
List<Note> notes = noteRepository.findById(userId)
.map(NoteUser::getNotes)
.orElse(null);
return notes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment