Java Streams: map() vs flatMap()
Java Streams: map() vs flatMap() In Java Streams, both map() and flatMap() are used to transform data — but they behave differently based on the output structure. Let's break it down with real examples. ✅ map() – One-to-One Transformation Transforms each element into another value (e.g., String to Integer ): List<String> names = List.of("Alice", "Bob"); List<Integer> lengths = names.stream() .map(String::length) .collect(Collectors.toList()); System.out.println(lengths); // Output: [5, 3] ✅ flatMap() – One-to-Many Flattening Each element is mapped to a Stream , and all streams are then flattened into a single stream: List<String> sentences = List.of("Hello world", "Java Streams"); List<String> words = sentences.stream() .flatMap(s -> Arrays.stream(s.split(" "))) .collect(Collectors.toList()); System.out.println(words);...