Posts

Showing posts with the label Java Streams

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);...

Java Streams: A Modern Way to Process Data

Java Streams: A Modern Way to Process Data Introduced in Java 8, the Stream API brings a functional approach to processing collections. With streams, you can perform operations like filtering , mapping , and reducing in a concise and readable way. 🔍 What is a Stream? A Stream represents a sequence of elements and supports sequential and parallel aggregate operations. List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println); Output: Alice ⚙️ Common Operations 1. filter() Filters elements based on a condition: List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5); nums.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); 2. map() Transforms each element: List<String> names = Arrays.asList("Java", "Pytho...