A2oz

What is the difference between Map and filter method in Java?

Published in Java Programming 2 mins read

The Map and Filter methods in Java are both used to process collections of data, but they serve different purposes:

Map Method

The Map method transforms each element in a collection into a new element, applying a specific function to each one. It doesn't change the original collection's size.

Example:

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

List<Integer> squaredNumbers = numbers.stream()
    .map(n -> n * n)
    .collect(Collectors.toList());

System.out.println(squaredNumbers); // Output: [1, 4, 9, 16, 25]

In this example, the map method squares each element in the numbers list, creating a new list squaredNumbers.

Filter Method

The Filter method creates a new collection containing only the elements that meet a specific condition. It reduces the original collection's size.

Example:

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

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

System.out.println(evenNumbers); // Output: [2, 4]

In this example, the filter method selects only the even numbers from the numbers list, creating a new list evenNumbers.

Key Differences:

  • Purpose: Map transforms elements, while filter selects elements based on a condition.
  • Output: Map creates a new collection with the same size, while filter creates a new collection with potentially fewer elements.
  • Operation: Map applies a function to each element, while filter checks each element against a condition.

In summary, Map is used for transforming elements, while Filter is used for selecting elements. Both methods are essential for manipulating and processing data in Java collections.

Related Articles