Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use flatMap() to elide nulls in a Stream
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Scratch {
public static void main(String[] args) {
final List<String> original =
Stream.of("a", "b", null, "c")
.collect(Collectors.toList());
final List<String>
withoutNulls =
original.stream()
.flatMap(s -> null == s ? Stream.empty() : Stream.of(s))
.collect(Collectors.toList());
System.out.printf("with nulls: %s\n", toString(original));
System.out.printf("without nulls: %s\n", toString(withoutNulls));
}
private static String toString(final List<String> stream) {
final AtomicInteger i = new AtomicInteger();
final StringBuffer stringBuffer = new StringBuffer();
stream.forEach(s -> {
if (i.getAndAdd(1) > 0)
stringBuffer.append(",");
stringBuffer.append(s);
});
return stringBuffer.toString();
}
}
@Bill

This comment has been minimized.

Copy link
Owner Author

commented Apr 24, 2019

I hate myself for writing Java 8 Stream code like this because, since Java Streams are called "streams" , I expect them to be immutable sequences like SICP streams or Clojure sequences. But they aren't! They are recipes for computation. And they are not reusable recipes for computation. So I'm always having to convert Streams to collections when instead, I'd like to be composing streams.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.