If you have a more complex scenario or donβt like @Aaron's answer for any reason, you can perform a flat matrix trick that creates a stream of one element for each outer element:
as.stream(). flatMap(a -> Stream.of(a.getX()). filter(x -> x != null). map(x -> a)). forEach(System.out::println);
Here we have a nested stream for each element, where you can perform any stateless operations ( map , filter , peek and flatMap ) that have a link to the source element. After the source element becomes unnecessary, you close flatMap and continue the source stream. Example:
Stream.of("a", "bb", "ccc", "dd", "eeee") .flatMap(a -> Stream.of(a.length()) .filter(x -> x > 2) .map(x -> a)) .forEach(System.out::println); // prints "ccc" and "eeee".
Or two filters:
Stream.of("a", "bb", "ccc", "dd", "eeee") .flatMap(a -> Stream.of(a.length()) .filter(x -> x > 2) .map(x -> a.charAt(0))
Of course, such simple scripts can be rewritten as @Aaron suggests, but in more complex cases, flatMap-capture might be the solution.
source share