Difference between filter and map function of stream API?

The filter() and map() methods are intermediate operations in the Java Stream API, but they serve different purposes. The filter() method is used to select elements that match a given condition, whereas the map() method is used to transform each element into another form while preserving the number of elements in the stream.

Key Points: • filter() is used for filtering data based on a condition. • map() is used for transforming or converting data. • filter() may reduce the number of elements in the stream. • map() processes every element and usually keeps the same number of elements. • Both methods are commonly used together in stream pipelines.

Difference Between filter() and map():

filter(): • Returns only elements that satisfy a condition. • Uses a Predicate<T>. • Can reduce the stream size.

map(): • Converts each element into another value or type. • Uses a Function<T, R>. • Processes all elements in the stream.

Example:

Suppose we have a list of numbers:

[1, 2, 3, 4, 5]

Using filter():

Keep only even numbers:

[2, 4]

Using map():

Multiply every number by 10:

[10, 20, 30, 40, 50]

Code Example:

import java.util.Arrays;
import java.util.List;

public class Demo {

    public static void main(String[] args) {

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

        System.out.println("Filter:");

        numbers.stream()

.filter(num -> num % 2 == 0)

               .forEach(System.out::println);

        System.out.println("Map:");

        numbers.stream()

.map(num -> num * 10)

               .forEach(System.out::println);
    }
}

Output:

Filter:

2
4

Map:

10
20
30
40
50

Real-World Example:

Employee List:

• filter() → Select employees whose salary is greater than ₹50,000. • map() → Extract employee names from employee objects.

Example:

employees.stream() .filter(emp -> emp.getSalary() > 50000)

         .map(Employee::getName)
         .forEach(System.out::println);

Benefits:

filter(): • Removes unwanted data • Improves data selection • Makes code more readable

map(): • Converts data into required formats • Simplifies transformations • Reduces manual looping logic

Interview Tip: A concise interview answer is:

"filter() is used to select elements that satisfy a condition and may reduce the number of elements in the stream. map() is used to transform each element into another value or type and processes all elements in the stream. In simple terms, filter() selects data, while map() transforms data."