Sitemap
Raghunath

Raghunath

Java Streams

3 min readMar 30, 2025

--

A Stream in Java is a sequence of elements that supports aggregate operations. Unlike collections, streams don’t store data but they process data on-demand through a pipeline of operations.

Complete Java Program demonstrating stream creation, manipulation and final operations with actual output for each block.

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


public class Main{
public static void main(String[] args) {

// From Collection
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream().forEach(System.out::println);
// Output:
// Alice
// Bob
// Charlie

// From Array
String[] cities = {"Paris", "London", "New jersy"};
Arrays.stream(cities).forEach(System.out::println);
// Output:
// Paris
// London
// New jersy

// Using Stream.of()
Stream.of("Java", "Python", "C++").forEach(System.out::println);
// Output:
// Java
// Python
// C++

// Stream.builder()
Stream<String> stream = Stream.<String>builder().add("One").add("Two").build();
stream.forEach(System.out::println);
// Output:
// One
// Two

// Stream.iterate()
Stream.iterate(0, n -> n + 2).limit(5).forEach(System.out::println);
// Output:
// 0
// 2
// 4
// 6
// 8

// Stream.generate()
Stream.generate(() -> "Hello").limit(3).forEach(System.out::println);
// Output:
// Hello
// Hello
// Hello

// filter()
names = List.of("Alex", "Bob", "Amanda");
names.stream().filter(n -> n.startsWith("A")).forEach(System.out::println);
// Output:
// Alex
// Amanda

// map()
names.stream().map(String::toUpperCase).forEach(System.out::println);
// Output:
// ALEX
// BOB
// AMANDA

// flatMap()
List<List<String>> nested = List.of(List.of("a", "b"), List.of("c"));
nested.stream().flatMap(List::stream).forEach(System.out::print);
// Output:
// abc

// distinct()
List<Integer> numbers = List.of(1, 2, 2, 3 , 4);
numbers.stream().distinct().forEach(System.out::println);
// Output:
// 1
// 2
// 3
// 4

// sorted()
names.stream().sorted().forEach(System.out::println);
// Output:
// Alex
// Amanda
// Bob

// peek()
names.stream().peek(System.out::println).map(String::toUpperCase).forEach(System.out::println);
// Output (mixed due to peek):
// Alex
// ALEX
// Bob
// BOB
// Amanda
// AMANDA

// limit() & skip()
Stream.of(1, 2, 3, 4, 5).limit(3).forEach(System.out::println);
// Output:
// 1
// 2
// 3

Stream.of(10, 20, 30, 40).skip(2).forEach(System.out::println);
// Output:
// 30
// 40

// mapToInt()
List<String> values = List.of("5", "10");
int sum = values.stream().mapToInt(Integer::parseInt).sum();
System.out.println(sum);
// Output:
// 15

// toArray()
String[] arr = names.stream().toArray(String[]::new);
System.out.println(Arrays.toString(arr));
// Output:
// [Alex, Bob, Amanda]

// reduce()
Optional<String> result = names.stream().reduce((a, b) -> a + "," + b);
System.out.println(result.get());
// Output:
// Alex,Bob,Amanda

// collect()
List<String> collected = names.stream().collect(Collectors.toList());
System.out.println(collected);
// Output:
// [Alex, Bob, Amanda]

// min() & max()
Optional<String> min = names.stream().min(Comparator.comparing(String::length));
Optional<String> max = names.stream().max(Comparator.comparing(String::length));
System.out.println(min.get()); // Output: Bob
System.out.println(max.get()); // Output: Amanda

// count()
long count = names.stream().count();
System.out.println(count);
// Output:
// 3

// anyMatch(), allMatch(), noneMatch()
boolean any = names.stream().anyMatch(n -> n.equals("Alex"));
boolean all = names.stream().allMatch(n -> n.length() > 2);
boolean none = names.stream().noneMatch(n -> n.equals("Zoe"));
System.out.println(any); // true
System.out.println(all); // true
System.out.println(none); // true

// findFirst()
Optional<String> first = names.stream().findFirst();
System.out.println(first.get());
// Output:
// Alex

// Grouping with groupingBy()
List<String> fruits = List.of("apple", "apricot", "banana", "blueberry");
Map<Character, List<String>> grouped = fruits.stream()
.collect(Collectors.groupingBy(f -> f.charAt(0)));
System.out.println(grouped);
// Output:
// {a=[apple, apricot], b=[banana, blueberry]}

// Conditional Logic (if/else)
names.stream().map(n -> n.equals("Alex") ? "Mr. Alex" : n).forEach(System.out::println);
// Output:
// Mr. Alex
// Bob
// Amanda

// Exception Handling in Streams
List<String> data = List.of("10", "20", "a", "30");
List<Integer> parsed = data.stream().map(s -> {
try {
return Integer.parseInt(s);
} catch (Exception e) {
return -1;
}
}).collect(Collectors.toList());
System.out.println(parsed);
// Output:
// [10, 20, -1, 30]

// Parallel vs Sequential Streams
System.out.println("Sequential:");
names.stream().forEach(System.out::println);
// Output:
// Alex
// Bob
// Amanda

System.out.println("Parallel:");
names.parallelStream().forEach(System.out::println);
// Output (order may vary):
// Amanda
// Alex
// Bob
}
}

Summary

Get Raghunath’s stories in your inbox

Join Medium for free to get updates from this writer.

Java Streams allow you to:

  • Write concise, declarative, and functional-style code
  • Easily handle collections with map-filter-reduce patterns
  • Scale with parallel processing when needed

Mastering streams boosts your Java productivity and makes your code more elegant and efficient.

--

--