Last active
November 19, 2018 01:01
-
-
Save codinko/7442277d712a4da28ecff5b9ca60bb76 to your computer and use it in GitHub Desktop.
java.util.Optional.map code snippet-1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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