</>
Skip to content
Java lessons (47/47)

Java — Streams

Creating streams

import java.util.*;
import java.util.stream.*;

// From collection
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> stream = names.stream();

// From array
Stream<Integer> arrStream = Arrays.stream(new Integer[]{1, 2, 3});

// From values
Stream<String> valStream = Stream.of("a", "b", "c");

// Infinite stream
Stream<Integer> infinite = Stream.iterate(0, n -> n + 2);

Intermediate operations

List<String> names = List.of("Alice", "Bob", "Charlie", "David");

// filter
names.stream().filter(n -> n.length() > 3).forEach(System.out::println);

// map
names.stream().map(String::toUpperCase).forEach(System.out::println);

// sorted
names.stream().sorted().forEach(System.out::println);

// distinct
Stream.of(1, 1, 2, 3, 3).distinct().forEach(System.out::println);

Terminal operations

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

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

// reduce
int sum = nums.stream().reduce(0, Integer::sum);

// forEach
nums.stream().forEach(System.out::println);

// count
long count = nums.stream().filter(n -> n > 3).count();

// anyMatch, allMatch, noneMatch
boolean hasEven = nums.stream().anyMatch(n -> n % 2 == 0);

// findFirst
Optional<Integer> first = nums.stream().findFirst();

Collectors

import java.util.stream.Collectors;

// Joining
String joined = names.stream().collect(Collectors.joining(", "));

// Grouping
Map<Integer, List<String>> byLength = names.stream()
    .collect(Collectors.groupingBy(String::length));

// Partitioning
Map<Boolean, List<Integer>> partitioned = nums.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));

Mini Practice

Write Java code that:

  1. Creates a stream from a list
  2. Chains filter, map, and reduce
  3. Uses Collectors to join strings
  4. Groups elements by a property

Up Next

In the next lesson, you'll learn about File Handling — reading and writing files.

Related Topics

Frequently Asked Questions about Streams

What is Streams in Java?

Streams is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Streams?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Streams.

Why is Streams important in Java?

Streams is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.