Java 8 Streams: Map vs Filter Operations

🚀 15 Days of Java 8 – #Day5: Transforming with `map()` What is the `map()` operation in streams, and how is it different from `filter()`? ✅ Answer: The `map()` operation is an intermediate operation that transforms each element of a stream into another object by applying a function to it. While `filter()` selects elements, `map()` changes them. - `filter(n -> n > 5)`: Takes an `Integer` and returns a `boolean`. The stream remains a stream of `Integer`s. - `map(s -> s.length())`: Takes a `String` and returns an `int`. The stream of `String`s is transformed into a stream of `Integer`s. //--- Code Snippet: Get a list of names' lengths --- List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); List<Integer> nameLengths = names.stream()   .map(name -> name.length())   .collect(Collectors.toList()); // Result: [5, 3, 7] //---------------------------------------------------- 💡 Takeaway: Use `filter()` when you want to reduce the number of elements in a stream. Use `map()` when you want to transform each element into something else. 📢 Filtering and mapping are the two most fundamental stream operations! 🚀 Day 6: Chaining operations into a pipeline! 💬 How would you use `map` to convert a list of strings to all uppercase? 👇 #Java #Java8 #StreamAPI #Map #FunctionalProgramming #DataTransformation #15DaysOfJava8

To view or add a comment, sign in

Explore content categories