🧊Array, List (Filter, Map, Reduce)
1. Filter (.filter())
.filter())What is it?
The filter() method creates a new collection with all elements that pass the test implemented by the provided function. It does not execute the function for empty elements and does not change the original collection.
How to use it?
Use it when you want to select a subset of items from a list/array based on a condition.
JavaScript Example
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter numbers that are divisible by 2 (even numbers)
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers);
// Output: [2, 4, 6, 8, 10]Java Example (Stream API)
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filter numbers that are divisible by 2 (even numbers)
List<Integer> evenNumbers = numbers.stream()
.filter(number -> number % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
// Output: [2, 4, 6, 8, 10]
}
}2. Map (.map())
.map())What is it?
The map() method creates a new collection populated with the results of calling a provided function on every element in the calling collection.
How to use it?
Use it when you want to transform every element in a list/array into something else (e.g., converting objects, performing math operations).
JavaScript Example
Java Example (Stream API)
3. Reduce (.reduce())
.reduce())What is it?
The reduce() method executes a user-supplied "reducer" callback function on each element of the collection, in order, passing in the return value from the calculation on the preceding element. The final result is a single value.
How to use it?
Use it when you want to derive a single value from a list/array (e.g., sum, product, average, or grouping objects).
JavaScript Example
Java Example (Stream API)
Last updated