import java.util.*;
import java.util.stream.*;
class Demo {
record User(String name, List<String> roles) {}
void example() {
var phrases = List.of("hello world", "foo bar baz", "java rocks");
// Split each phrase into words, then flatten
List<String> allWords = phrases.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.toList();
System.out.println(allWords);
// [hello, world, foo, bar, baz, java, rocks]
// All distinct roles across all users
var users = List.of(
new User("Alice", List.of("admin", "editor")),
new User("Bob", List.of("editor", "viewer")),
new User("Cara", List.of("admin"))
);
Set<String> roles = users.stream()
.flatMap(u -> u.roles().stream())
.collect(Collectors.toSet());
System.out.println(roles); // [admin, editor, viewer]
// Optional<T> as Stream<T> via Optional::stream — common with flatMap
Optional<String> opt = Optional.of("hello");
String joined = Stream.of(opt, Optional.<String>empty(), Optional.of("world"))
.flatMap(Optional::stream)
.collect(Collectors.joining(" "));
System.out.println(joined); // hello world
}
}
Create a free account and build your private vault. Share publicly whenever you want.