Java.Java8.What is the purpose of the filter() method in streams?

Great question again, Stanley! 🔥
The filter() method is one of the most commonly used tools in the Stream API, and it’s essential for writing clean, expressive code.

✅ What is the filter() Method?

Stream<T> filter(Predicate<? super T> predicate)

📌 Purpose:

  • To select only the elements that match a condition
  • It uses a Predicate<T> (a function that returns true or false)
  • Returns a new stream with only the matching elements

🧠 Simple Example:

Stream<String> stream = Stream.of("apple", "banana", "avocado");

stream
  .filter(s -> s.startsWith("a"))
  .forEach(System.out::println);

// Output:
// apple
// avocado

✅ Key Characteristics

FeatureDescription
💬 FunctionalAccepts a lambda or method reference returning boolean
🎯 SelectiveFilters elements that satisfy a given condition
💡 LazyIt doesn’t run until a terminal operation is called
🔁 Non-mutatingIt does not modify the original source

📌 Predicate Interface:

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

So you can pass any function like:

  • x -> x > 10
  • s -> s.contains("foo")
  • String::isEmpty

🔧 Practical Examples

✅ 1. Filter even numbers

List<Integer> numbers = List.of(1, 2, 3, 4, 5);

numbers.stream()
    .filter(n -> n % 2 == 0)
    .forEach(System.out::println); // Output: 2, 4

✅ 2. Filter non-null values

List<String> list = Arrays.asList("Java", null, "Streams");

list.stream()
    .filter(Objects::nonNull)
    .forEach(System.out::println); // Output: Java, Streams

🧠 Chaining filter() with other operations

List<String> names = List.of("Anna", "Bob", "Alex", "John");

List<String> result = names.stream()
    .filter(n -> n.startsWith("A"))
    .map(String::toUpperCase)
    .collect(Collectors.toList());

System.out.println(result); // Output: [ANNA, ALEX]

✅ Summary

Featurefilter() in Streams
📌 PurposeKeeps elements that match a condition
💡 AcceptsA Predicate<T>
📤 ReturnsA new Stream<T> with filtered elements
🧠 Common usageWith .map(), .collect(), .forEach()
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.