Common Java Stream API Programming and Operations
This article introduces Java 8's Stream API, explains how to create streams from collections and arrays, and demonstrates a wide range of intermediate and terminal operations with clear code examples to help developers write concise, efficient, and readable Java code.
Java 8 introduced the Stream API, a high‑level abstraction that allows developers to process data in a declarative, pipeline‑style manner similar to SQL queries, greatly improving productivity and code readability.
Creating streams : Streams can be created from collections using stream() for sequential processing or parallelStream() for parallel execution. Arrays can be turned into streams with Stream.of(), Stream.generate(), Stream.iterate(), IntStream, and LongStream. Example:
List<String> list = new ArrayList<>();
Stream<String> s1 = list.stream();
Stream<String> s2 = list.parallelStream();
String[] strs = new String[3];
Stream<String> s3 = Arrays.stream(strs);
Stream<String> s4 = Stream.of("Apple", "Orange", "Banana");
Stream<Double> s5 = Stream.generate(Math::random).limit(5);
IntStream intStream = IntStream.range(1, 5);
LongStream longStream = LongStream.rangeClosed(1, 5);Intermediate operations include: filter – retains elements that satisfy a predicate. map and flatMap – transform each element; flatMap also flattens nested structures. mapToInt, mapToLong, mapToDouble – convert elements to primitive streams for numeric calculations. sorted – orders elements, requiring Comparable or a custom comparator. distinct – removes duplicate elements. limit, skip – truncate or bypass a number of elements. peek – performs an action on each element for debugging.
Sample code for filtering and mapping:
public static void filterTest(List<Integer> lists) {
List<Integer> result = lists.stream()
.filter(i -> Objects.equals(1, i))
.toList();
result.forEach(System.out::println);
}
public static void mapTest(List<String> lists) {
lists.stream().map(String::toLowerCase).toList();
lists.forEach(System.out::println);
}
public static void flatMapTest(List<List<String>> lists) {
lists = Arrays.asList(
Arrays.asList("Java", "Kotlin"),
Arrays.asList("Python", "Ruby"),
Arrays.asList("JavaScript", "TypeScript")
);
List<String> flat = lists.stream().flatMap(List::stream).toList();
flat.forEach(System.out::println);
}Terminal operations : forEach – iterates over each element. collect – gathers elements into collections, maps, or strings using collectors such as toList(), toSet(), toMap(), and joining(). partitioningBy – splits a stream into two groups based on a predicate. findFirst and findAny – retrieve the first or any matching element. anyMatch, noneMatch, allMatch – evaluate boolean conditions across the stream.
Example of collecting and matching:
Map<Integer, Student> studentMap = students.stream()
.collect(Collectors.toMap(Student::getAge, Function.identity(), (e1, e2) -> e1));
String names = students.stream()
.map(Student::getName)
.collect(Collectors.joining(","));
boolean hasAgeOne = students.stream()
.anyMatch(s -> Objects.equals(1, s.getAge()));
Student first = students.stream()
.filter(s -> Objects.equals(1, s.getAge()))
.findFirst()
.orElse(null);The article concludes that the covered Stream operations represent the essential toolkit for everyday Java backend development, enabling concise and efficient data processing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
