Filtering with Java 8 Streams: Using filter() Operation

🚀 15 Days of Java 8 – #Day4: Filtering with Streams How do you use the `filter()` operation in the Stream API to select elements that match a certain criteria? ✅ Answer: The `filter()` operation is an intermediate operation that takes a `Predicate` (a function that returns a boolean) and returns a new stream containing only the elements that match the predicate. //--- Old Way (for-each loop) --- List<String> longNames = new ArrayList<>(); for (String name : names) {  if (name.length() > 5) {   longNames.add(name);  } } //--- New Way (Stream.filter) --- List<String> longNames = names.stream()  .filter(name -> name.length() > 5)  .collect(Collectors.toList()); //-------------------------------- 💡 Takeaway: The `filter()` operation is your go-to tool for selectively choosing elements from a collection based on a condition. It's the `if` statement of the stream world. 📢 Declarative code is easier to read and reason about! 🚀 Day 5: Transforming elements with `map()`! 💬 How would you filter a list of integers to get only the positive numbers? 👇 #Java #Java8 #StreamAPI #Filter #Lambda #CleanCode #15DaysOfJava8

To view or add a comment, sign in

Explore content categories