Skip to content

Instantly share code, notes, and snippets.

@Bill
Created April 24, 2019 22:32
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 Bill/709fdba6daae4d97d313535a80311d0a to your computer and use it in GitHub Desktop.
Save Bill/709fdba6daae4d97d313535a80311d0a to your computer and use it in GitHub Desktop.
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
Copy link
Author

Bill 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