Created
April 24, 2019 22:32
-
-
Save Bill/709fdba6daae4d97d313535a80311d0a to your computer and use it in GitHub Desktop.
Use flatMap() to elide nulls in a Stream
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.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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hate myself for writing Java 8
Stream
code like this because, since JavaStream
s 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 convertStream
s to collections when instead, I'd like to be composing streams.