// Created on savesnippets.com · https://savesnippets.com/tsSgsoifKTPokx import java.util.*; import java.util.stream.*; class Demo { record User(String name, List roles) {} void example() { var phrases = List.of("hello world", "foo bar baz", "java rocks"); // Split each phrase into words, then flatten List 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 roles = users.stream() .flatMap(u -> u.roles().stream()) .collect(Collectors.toSet()); System.out.println(roles); // [admin, editor, viewer] // Optional as Stream via Optional::stream — common with flatMap Optional opt = Optional.of("hello"); String joined = Stream.of(opt, Optional.empty(), Optional.of("world")) .flatMap(Optional::stream) .collect(Collectors.joining(" ")); System.out.println(joined); // hello world } }