Last active
August 9, 2017 00:45
-
-
Save felipebelluco/defa683a7f9d437488d3a46e72665af2 to your computer and use it in GitHub Desktop.
Concise way to get a null safe Stream from a Collection.
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
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
List<String> names = null; | |
// NPE!!! | |
names.stream().filter(Objects::nonNull).forEach(System.out::println); | |
// It's ok! But instead of this... | |
Optional.ofNullable(names).orElseGet(ArrayList::new).stream() | |
.filter(Objects::nonNull) | |
.forEach(System.out::println); | |
// Use this! | |
StreamUtil.ofNullable(names).filter(Objects::nonNull).forEach(System.out::println); | |
} | |
} |
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
import java.util.Collection; | |
import java.util.Optional; | |
import java.util.stream.Stream; | |
public class StreamUtil { | |
static <T> Stream<T> ofNullable(Collection<T> collection) { | |
return Optional.ofNullable(collection).map(Collection::stream).orElseGet(Stream::empty); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment