Claude
Skills
Sign in
Back

java-streams-api

Included with Lifetime
$97 forever

Use when Java Streams API for functional-style data processing. Use when processing collections with streams.

Backend & APIs

What this skill does


# Java Streams API

Master Java's Streams API for functional-style operations on collections,
enabling declarative data processing with operations like filter, map, and
reduce.

## Introduction to Streams

Streams provide a functional approach to processing collections of objects.
Unlike collections, streams don't store elements - they convey elements from
a source through a pipeline of operations.

**Creating streams:**

```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamCreation {
    public static void main(String[] args) {
        // From collection
        List<String> list = Arrays.asList("a", "b", "c");
        Stream<String> stream1 = list.stream();

        // From array
        String[] array = {"a", "b", "c"};
        Stream<String> stream2 = Arrays.stream(array);

        // Using Stream.of()
        Stream<String> stream3 = Stream.of("a", "b", "c");

        // Empty stream
        Stream<String> stream4 = Stream.empty();

        // Infinite stream with limit
        Stream<Integer> stream5 = Stream.iterate(0, n -> n + 1)
                                       .limit(10);
    }
}
```

## Intermediate Operations

Intermediate operations return a new stream and are lazy - they don't
execute until a terminal operation is invoked.

**filter() - Select elements:**

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

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

        // Filter even numbers
        List<Integer> evenNumbers = numbers.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());
        // Result: [2, 4, 6, 8]

        // Multiple filters can be chained
        List<Integer> result = numbers.stream()
            .filter(n -> n > 3)
            .filter(n -> n < 7)
            .collect(Collectors.toList());
        // Result: [4, 5, 6]
    }
}
```

**map() - Transform elements:**

```java
public class MapExample {
    public static void main(String[] args) {
        List<String> words = List.of("hello", "world");

        // Convert to uppercase
        List<String> uppercase = words.stream()
            .map(String::toUpperCase)
            .collect(Collectors.toList());
        // Result: ["HELLO", "WORLD"]

        // Get string lengths
        List<Integer> lengths = words.stream()
            .map(String::length)
            .collect(Collectors.toList());
        // Result: [5, 5]

        // Chain transformations
        List<Integer> doubled = List.of(1, 2, 3).stream()
            .map(n -> n * 2)
            .collect(Collectors.toList());
        // Result: [2, 4, 6]
    }
}
```

**flatMap() - Flatten nested structures:**

```java
public class FlatMapExample {
    public static void main(String[] args) {
        List<List<Integer>> nested = List.of(
            List.of(1, 2),
            List.of(3, 4),
            List.of(5, 6)
        );

        // Flatten to single list
        List<Integer> flattened = nested.stream()
            .flatMap(List::stream)
            .collect(Collectors.toList());
        // Result: [1, 2, 3, 4, 5, 6]

        // Split strings and flatten
        List<String> sentences = List.of("hello world", "foo bar");
        List<String> words = sentences.stream()
            .flatMap(s -> Arrays.stream(s.split(" ")))
            .collect(Collectors.toList());
        // Result: ["hello", "world", "foo", "bar"]
    }
}
```

**distinct() and sorted():**

```java
public class DistinctSortedExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(5, 2, 8, 2, 1, 5, 3);

        // Remove duplicates
        List<Integer> distinct = numbers.stream()
            .distinct()
            .collect(Collectors.toList());
        // Result: [5, 2, 8, 1, 3]

        // Sort ascending
        List<Integer> sorted = numbers.stream()
            .sorted()
            .collect(Collectors.toList());
        // Result: [1, 2, 2, 3, 5, 5, 8]

        // Sort descending
        List<Integer> descending = numbers.stream()
            .sorted((a, b) -> b - a)
            .collect(Collectors.toList());

        // Distinct and sorted
        List<Integer> distinctSorted = numbers.stream()
            .distinct()
            .sorted()
            .collect(Collectors.toList());
        // Result: [1, 2, 3, 5, 8]
    }
}
```

**peek() - Debug or perform side effects:**

```java
public class PeekExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);

        // Debug stream pipeline
        List<Integer> result = numbers.stream()
            .peek(n -> System.out.println("Original: " + n))
            .map(n -> n * 2)
            .peek(n -> System.out.println("Doubled: " + n))
            .filter(n -> n > 5)
            .peek(n -> System.out.println("Filtered: " + n))
            .collect(Collectors.toList());
    }
}
```

## Terminal Operations

Terminal operations produce a result or side effect and close the stream.

**collect() - Gather results:**

```java
import java.util.stream.Collectors;
import java.util.Map;
import java.util.Set;

public class CollectExample {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "banana", "cherry");

        // To List
        List<String> list = words.stream()
            .collect(Collectors.toList());

        // To Set
        Set<String> set = words.stream()
            .collect(Collectors.toSet());

        // To Map
        Map<String, Integer> map = words.stream()
            .collect(Collectors.toMap(
                w -> w,              // Key
                String::length       // Value
            ));
        // Result: {apple=5, banana=6, cherry=6}

        // Joining strings
        String joined = words.stream()
            .collect(Collectors.joining(", "));
        // Result: "apple, banana, cherry"

        // Grouping by length
        Map<Integer, List<String>> grouped = words.stream()
            .collect(Collectors.groupingBy(String::length));
        // Result: {5=[apple], 6=[banana, cherry]}
    }
}
```

**reduce() - Combine elements:**

```java
public class ReduceExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);

        // Sum with identity
        int sum = numbers.stream()
            .reduce(0, (a, b) -> a + b);
        // Result: 15

        // Product
        int product = numbers.stream()
            .reduce(1, (a, b) -> a * b);
        // Result: 120

        // Max value
        Optional<Integer> max = numbers.stream()
            .reduce((a, b) -> a > b ? a : b);
        // Result: Optional[5]

        // Using method reference
        int sum2 = numbers.stream()
            .reduce(0, Integer::sum);

        // String concatenation
        String concatenated = List.of("a", "b", "c").stream()
            .reduce("", (a, b) -> a + b);
        // Result: "abc"
    }
}
```

**forEach() and forEachOrdered():**

```java
public class ForEachExample {
    public static void main(String[] args) {
        List<String> words = List.of("hello", "world");

        // Print each element
        words.stream()
            .forEach(System.out::println);

        // Parallel stream with ordered iteration
        words.parallelStream()
            .forEachOrdered(System.out::println);

        // With side effects (use cautiously)
        List<String> results = new ArrayList<>();
        words.stream()
            .map(String::toUpperCase)
            .forEach(results::add);
    }
}
```

**count(), anyMatch(), allMatch(), noneMatch():**

```java
public class MatchingExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);

        // Count elements
        long count = numbers.stream()
            .filter(n -> n > 2)
           

Related in Backend & APIs