JAVA 8 STREAMS

JAVA 8 STREAMS

1. map() – transform each element

 Use when:

You want to transform each element of the stream into something else.

Example:

Convert a list of names to uppercase.

List<String> names = Arrays.asList("john", "jane", "jack");

List<String> upper = names.stream()

                          .map(String::toUpperCase)

                          .collect(Collectors.toList());

2. filter() – keep only elements that match a condition

Use when:

You want to remove unwanted elements based on a condition.

Example:

Get only even numbers from a list.

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

List<Integer> evens = nums.stream()

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

                          .collect(Collectors.toList());

3. collect() – gather the result

Use when:

You're done with processing the stream and want to collect the results into a list, set, map, etc.

Example:

Get a list of squares:

List<Integer> squares = nums.stream()

                            .map(n -> n * n)

                            .collect(Collectors.toList());

4. flatMap() – flatten nested structure

Use when:

You have streams inside streams (like List<List<T>>), and you want a flat stream.

Example:

Flatten a list of lists:

List<List<String>> nested = Arrays.asList(

    Arrays.asList("a", "b"),

    Arrays.asList("c", "d")

);

List<String> flat = nested.stream()

                          .flatMap(Collection::stream)

                          .collect(Collectors.toList());

Also useful when splitting strings into characters!

5. IntStream, DoubleStream, LongStream – for primitive streams

Use when:

You're working with primitive types to avoid boxing/unboxing overhead.

Example:

Sum of numbers using IntStream:

int sum = IntStream.range(1, 6)  // 1 to 5

                   .sum();

TL;DR CHEAT SHEET

Use this

When you want to...

map() Transform each element

filter() Remove elements based on a condition

flatMap() Flatten nested streams

collect() Gather final results into List/Set/Map

IntStream Handle primitive ints efficiently

.chars() Convert String → IntStream (char by char)




To view or add a comment, sign in

More articles by Machilikanth Java developer

Explore content categories