Streams: filter, map and collect

A conveyor belt for data

A stream takes the items of a collection and passes them through a series of steps, like a factory conveyor belt. At each station something happens: keep only some items, change them, count them...

Think of it like this: Fruit on a conveyor belt: station 1 throws away bad fruit (filter), station 2 peels them (map), and at the end they are packed into a box (collect).

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

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

        List<Integer> evenSquares = nums.stream()
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .collect(Collectors.toList());

        System.out.println(evenSquares);
    }
}

Output

[4, 16, 36, 64]
StepDoes
filter(test)keep only items where the test is true
map(change)turn each item into something else
sorted()sort the items
distinct()remove duplicates
limit(n)keep only the first n items
collect(...)pack the results into a collection

Working with Strings

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

public class Main {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("ravi", "asha", "meera", "arjun", "anu");
        List<String> aNames = names.stream()
                .filter(n -> n.startsWith("a"))
                .map(String::toUpperCase)
                .sorted()
                .collect(Collectors.toList());
        System.out.println(aNames);

        String joined = names.stream().collect(Collectors.joining(", "));
        System.out.println(joined);
    }
}

Output

[ANU, ARJUN, ASHA]
ravi, asha, meera, arjun, anu

Remember: A stream doesn't change the original list. It produces a new result.

HOME LABS COMMUNITY DASHBOARD