Skip to content

Instantly share code, notes, and snippets.

@felipebelluco
Last active August 9, 2017 00:45
Show Gist options
  • Save felipebelluco/defa683a7f9d437488d3a46e72665af2 to your computer and use it in GitHub Desktop.
Save felipebelluco/defa683a7f9d437488d3a46e72665af2 to your computer and use it in GitHub Desktop.
Concise way to get a null safe Stream from a Collection.
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);
}
}
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