The two core features of Java 8 are Lambda expressions and Stream API, which make the code more concise, readable and functional. 1. Lambda expressions are anonymous functions, used to simplify the implementation of functional interfaces, such as replacing the anonymous class of Comparator with (a, b) -> a.compareTo(b); 2. The Stream API provides a declarative data processing pipeline, supporting chain operations, such as filter, map, reduce, etc.; 3. Intermediate operations (such as filter, map) are lazy, and terminal operations (such as forEach, collect) trigger execution; 4. Common patterns include filtering mapping, flatMap flattening, reduce aggregation, and Collectors collection results; 5. Best practices include avoiding side effects, not reusing streams, and using parallelStream with caution; 6. Not suitable for simple loops or performance-sensitive scenarios. Mastering them can significantly improve the efficiency and code quality of collection processing, which is a necessary skill for modern Java development.
Java 8 introduced two game-changing features: Lambda expressions and the Stream API . Together, they revolutionized how developers write, read, and maintain Java code—especially when dealing with collections. This guide walks you through both concepts with practical examples, common patterns, and best practices.

What Are Lambda Expressions?
A lambda expression is a concise way to represent an anonymous function—a block of code that can be passed around and executed later. It's particularly useful for functional programming in Java.
Before Java 8, you'd often use anonymous inner classes:

Collections.sort(names, new Comparator<String>() { public int compare(String a, String b) { return a.compareTo(b); } });
With lambdas, the same code becomes:
Collections.sort(names, (a, b) -> a.compareTo(b));
Syntax of a Lambda
(parameters) -> expression
Or for multiple statements:

(parameters) -> { statements; }
Key Points:
- Lambdas work only with functional interfaces (interfaces with exactly one abstract method).
- Common functional interfaces in
java.util.function
include:-
Predicate<T>
:boolean test(T t)
-
Function<T, R>
:R apply(T t)
-
Consumer<T>
:void accept(T t)
-
Supplier<T>
:T get()
-
UnaryOperator<T>
,BinaryOperator<T>
-
Example Usage
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Predicate: filter names starting with "A" Predicate<String> startsWithA = name -> name.startsWith("A"); names.stream() .filter(startsWithA) .forEach(System.out::println); // Output: Alice
Note: System.out::println
is a method reference , shorthand for x -> System.out.println(x)
.
Introduction to Streams
The Stream API allows you to process sequences of elements (like collections) in a declarative way—focusing on what to do, not how to do it.
Streams are not data structures. They don't store data, nor do they modify the source. Instead, they carry data through a pipeline of operations.
Creating a Stream
// From a collection List<String> list = Arrays.asList("a", "b", "c"); Stream<String> stream = list.stream(); // From an array Stream<Integer> arrStream = Arrays.stream(new Integer[]{1, 2, 3}); // From values Stream<String> valueStream = Stream.of("hello", "world"); // Infinite streams Stream.iterate(0, n -> n 2).limit(5); // 0, 2, 4, 6, 8
Stream Operations: Intermediate vs Terminal
Streams support a chain of operations divided into two types:
1. Intermediate Operations (return a new Stream)
These are lazy —they don't execute until a terminal operation is called.
-
filter(Predicate)
-
map(Function)
-
flatMap(Function)
-
distinct()
-
sorted()
-
peek(Consumer)
-
limit(n)
-
skip(n)
2. Terminal Operations (trigger processing)
These consume the stream and produce a result or side effect.
-
forEach(Consumer)
-
collect(Collector)
-
reduce(BinaryOperator)
-
count()
-
anyMatch(Predicate)
-
findFirst()
-
toArray()
Example Pipeline
List<String> result = names.stream() .filter(name -> name.length() > 4) .map(String::toUpperCase) .sorted() .collect(Collectors.toList());
This reads naturally: “Filter long names, convert to uppercase, sort, and collect.”
Common Stream Patterns
Filtering and Mapping
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> evenSquares = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .collect(Collectors.toList()); // [4, 16, 36]
FlatMap for Nested Structures
Use flatMap
to flatten streams of streams.
List<List<String>> listOfLists = Arrays.asList( Arrays.asList("a", "b"), Arrays.asList("c", "d") ); List<String> all = listOfLists.stream() .flatMap(List::stream) .collect(Collectors.toList()); // ["a", "b", "c", "d"]
Reduction with reduce()
Optional<Integer> sum = nums.stream() .reduce((a, b) -> ab); // Optional[21]
Or with identity:
int total = nums.stream().reduce(0, Integer::sum); // 21
Collecting Results
Collectors
is your go-to utility for gathering stream output.
// To List List<String> list = stream.collect(Collectors.toList()); // To Set Set<String> set = stream.collect(Collectors.toSet()); // To String with joining String joined = stream.collect(Collectors.joining(", ")); // Grouping by a property Map<Integer, List<String>> byLength = names.stream() .collect(Collectors.groupingBy(String::length));
Example:
// Group names by length { 3: ["Bob"], 5: ["Alice"], 7: ["Charlie"] }
Partitioning
Split based on a predict:
Map<Boolean, List<String>> partitioned = names.stream() .collect(Collectors.partitioningBy(s -> s.startsWith("A"))); // true: [Alice], false: [Bob, Charlie]
Performance and Best Practices
- Streams are lazy : Intermediate operations don't run until terminal operation is invoked.
- Avoid side effects in lambdas. They should be stateless.
- Prefer streams for readability, but don't overuse them for simple loops.
- Use
parallelStream()
with caution—only when data is large and operations are independent. - Don't reuse streams: A stream can be consumed only once.
Stream<String> s = list.stream(); s.forEach(System.out::println); // OK s.forEach(System.out::println); // IllegalStateException!
When Not to Use Streams
- Simple loops with side effects (eg, updating external variables).
- Performance-critical loops where overhead matters.
- When code becomes less readable (eg, deeply nested flatMaps).
Sometimes a plain for
loop is clearer.
Summary
Java 8's lambdas and streams make code more expressive and functional. You can:
- Replace verbose anonymous classes with clean lambda syntax.
- Chain operations on data using streams.
- Use built-in collectors for grouping, joining, and reducing.
- Write declarative, readable code.
They don't replace traditional loops entirely, but they're powerful tools when used appropriately.
Basically, if you're working with collections in Java, learning streams and lambdas is essential—and once you get used to them, you'll wonder how you lived without.
The above is the detailed content of A Comprehensive Guide to Java 8 Streams and Lambdas. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Enums in Java are special classes that represent fixed number of constant values. 1. Use the enum keyword definition; 2. Each enum value is a public static final instance of the enum type; 3. It can include fields, constructors and methods to add behavior to each constant; 4. It can be used in switch statements, supports direct comparison, and provides built-in methods such as name(), ordinal(), values() and valueOf(); 5. Enumeration can improve the type safety, readability and flexibility of the code, and is suitable for limited collection scenarios such as status codes, colors or week.

Interface Isolation Principle (ISP) requires that clients not rely on unused interfaces. The core is to replace large and complete interfaces with multiple small and refined interfaces. Violations of this principle include: an unimplemented exception was thrown when the class implements an interface, a large number of invalid methods are implemented, and irrelevant functions are forcibly classified into the same interface. Application methods include: dividing interfaces according to common methods, using split interfaces according to clients, and using combinations instead of multi-interface implementations if necessary. For example, split the Machine interfaces containing printing, scanning, and fax methods into Printer, Scanner, and FaxMachine. Rules can be relaxed appropriately when using all methods on small projects or all clients.

Java supports asynchronous programming including the use of CompletableFuture, responsive streams (such as ProjectReactor), and virtual threads in Java19. 1.CompletableFuture improves code readability and maintenance through chain calls, and supports task orchestration and exception handling; 2. ProjectReactor provides Mono and Flux types to implement responsive programming, with backpressure mechanism and rich operators; 3. Virtual threads reduce concurrency costs, are suitable for I/O-intensive tasks, and are lighter and easier to expand than traditional platform threads. Each method has applicable scenarios, and appropriate tools should be selected according to your needs and mixed models should be avoided to maintain simplicity

There are three main differences between Callable and Runnable in Java. First, the callable method can return the result, suitable for tasks that need to return values, such as Callable; while the run() method of Runnable has no return value, suitable for tasks that do not need to return, such as logging. Second, Callable allows to throw checked exceptions to facilitate error transmission; while Runnable must handle exceptions internally. Third, Runnable can be directly passed to Thread or ExecutorService, while Callable can only be submitted to ExecutorService and returns the Future object to

In Java, enums are suitable for representing fixed constant sets. Best practices include: 1. Use enum to represent fixed state or options to improve type safety and readability; 2. Add properties and methods to enums to enhance flexibility, such as defining fields, constructors, helper methods, etc.; 3. Use EnumMap and EnumSet to improve performance and type safety because they are more efficient based on arrays; 4. Avoid abuse of enums, such as dynamic values, frequent changes or complex logic scenarios, which should be replaced by other methods. Correct use of enum can improve code quality and reduce errors, but you need to pay attention to its applicable boundaries.

JavaNIO is a new IOAPI introduced by Java 1.4. 1) is aimed at buffers and channels, 2) contains Buffer, Channel and Selector core components, 3) supports non-blocking mode, and 4) handles concurrent connections more efficiently than traditional IO. Its advantages are reflected in: 1) Non-blocking IO reduces thread overhead, 2) Buffer improves data transmission efficiency, 3) Selector realizes multiplexing, and 4) Memory mapping speeds up file reading and writing. Note when using: 1) The flip/clear operation of the Buffer is easy to be confused, 2) Incomplete data needs to be processed manually without blocking, 3) Selector registration must be canceled in time, 4) NIO is not suitable for all scenarios.

Javaprovidesmultiplesynchronizationtoolsforthreadsafety.1.synchronizedblocksensuremutualexclusionbylockingmethodsorspecificcodesections.2.ReentrantLockoffersadvancedcontrol,includingtryLockandfairnesspolicies.3.Conditionvariablesallowthreadstowaitfor

Java's class loading mechanism is implemented through ClassLoader, and its core workflow is divided into three stages: loading, linking and initialization. During the loading phase, ClassLoader dynamically reads the bytecode of the class and creates Class objects; links include verifying the correctness of the class, allocating memory to static variables, and parsing symbol references; initialization performs static code blocks and static variable assignments. Class loading adopts the parent delegation model, and prioritizes the parent class loader to find classes, and try Bootstrap, Extension, and ApplicationClassLoader in turn to ensure that the core class library is safe and avoids duplicate loading. Developers can customize ClassLoader, such as URLClassL
