riven

Riven

Riven

Filter stream java with example

What is a Stream in Java?

A Stream in Java is a sequence of elements that can be processed in a functional style. Streams are part of the Java 8 Stream API, allowing developers to perform operations on collections in a more expressive and declarative way.

Filtering with Streams

Filtering is one of the most common operations performed on streams. It allows you to selectively process elements based on specific criteria using the filter method.

How the filter Method Works

  • Syntax: Stream<T> filter(Predicate<? super T> predicate)
  • Input: A Predicate (a functional interface that returns a boolean) that defines the criteria for filtering elements.
  • Output: A new stream containing only the elements that match the predicate.

Basic Example of Filtering with Streams

Let’s start with a simple example where we filter a list of integers to find only the even numbers.

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FilterStreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Filtering even numbers using a stream
        List<Integer> evenNumbers = numbers.stream()
                                            .filter(n -> n % 2 == 0)
                                            .collect(Collectors.toList());

        System.out.println("Even numbers: " + evenNumbers);
    }
}
				
			

Explanation of the Example

  1. Stream Creation: numbers.stream() creates a sequential stream from the list of integers.
  2. Filtering: The filter method uses a lambda expression n -> n % 2 == 0 to keep only even numbers.
  3. Collecting: The collect(Collectors.toList()) method gathers the filtered results into a new list.

More Complex Filtering Example

Let’s consider an example where we filter a list of custom objects. Assume we have a Person class and we want to filter out people older than 18.

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class FilterPersonExample {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 22),
            new Person("Bob", 17),
            new Person("Charlie", 19),
            new Person("David", 15)
        );

        // Filtering people older than 18
        List<Person> adults = people.stream()
                                    .filter(person -> person.getAge() > 18)
                                    .collect(Collectors.toList());

        System.out.println("Adults: " + adults);
    }
}
				
			

Explanation of the Complex Example

  1. Custom Class: The Person class has a name and age.
  2. Stream Creation: people.stream() creates a stream from the list of Person objects.
  3. Filtering: The predicate person -> person.getAge() > 18 filters out people under 19.
  4. Collecting: The filtered results are collected into a new list of adults.

Chaining Multiple Operations

Streams support method chaining, allowing you to perform multiple operations in a single pipeline. Here’s an example that combines filtering with mapping.

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FilterAndMapExample {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 22),
            new Person("Bob", 17),
            new Person("Charlie", 19),
            new Person("David", 15)
        );

        // Filtering adults and collecting their names
        List<String> adultNames = people.stream()
                                         .filter(person -> person.getAge() > 18)
                                         .map(Person::toString) // Convert Person to String
                                         .collect(Collectors.toList());

        System.out.println("Adult Names: " + adultNames);
    }
}
				
			

Explanation of Chained Operations

  1. Filter: First, we filter out adults.
  2. Map: The map method converts each Person object to its string representation.
  3. Collect: Finally, we collect the results into a list of strings.

Best Practices for Using Streams and Filtering

  1. Use Functional Interfaces: Utilize lambda expressions or method references for clear and concise filtering.
  2. Avoid Side Effects: Ensure your filtering logic does not modify shared state or have side effects.
  3. Keep Filters Simple: Simple predicates enhance readability and maintainability.
  4. Consider Performance: For large datasets, consider using parallel streams if appropriate, but always benchmark performance.
Java do-while loop with example
Java do-while loop with example The do-while loop is a control flow statement in Java that allows for...
Set in java (Interface)
Set in java example In Java, the Set interface is part of the Java Collections Framework and represents...
Threads in java
Threads in java with example Threads are a fundamental concept in programming that enable concurrent...
TreeMap in Java with example
what is Treemap in java with example in Java, a TreeMap is part of the Java Collections Framework and...
Switch statement in java
Java switch statement The switch statement in Java is a powerful control flow structure that allows you...
Bean life cycle in spring
Bean life cycle in spring with example Spring Framework is a powerful tool for building Java applications,...
Filewriter in java with example
filewriter in java with example Writing to files in Java is a crucial skill for any developer, enabling...
Java arraylist with example
Java arraylist with example In Java, the ArrayList class is part of the Java Collections Framework and...
Continue statement in java
Continue statement in java The continue statement in Java is a control flow statement that alters the...
parallel stream in java
Parallel Stream in java Parallel streams automatically split the source data into multiple chunks and...