Method References in Stream Pipelines
Demonstrates four types of method references (static, instance, arbitrary object, constructor) to create concise and readable functional expressions.
Code
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class MethodReferences {
static String toUpper(String s) {
return s.toUpperCase();
}
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "charlie");
// Static method reference
List<String> upper = names.stream()
.map(MethodReferences::toUpper)
.toList();
// Instance method reference (arbitrary object)
List<String> sorted = names.stream()
.sorted(String::compareTo)
.toList();
// Instance method reference (specific object)
var printer = new Object() {
void print(String s) { System.out.println(s); }
};
upper.forEach(printer::print);
// Constructor reference
List<StringBuilder> builders = names.stream()
.map(StringBuilder::new)
.toList();
// Array constructor reference
String[] array = names.stream().toArray(String[]::new);
// Built-in method references
int totalLength = names.stream()
.mapToInt(String::length)
.sum();
System.out.println("Sorted: " + sorted);
System.out.println("Array length: " + array.length);
System.out.println("Total chars: " + totalLength);
}
}How it works
The working surface is the class MethodReferences and the functions toUpper and main — everything else is wiring.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Applying it
The primary signature is static String toUpper(String s)
The demo output is labeled (Sorted:, Array length:, Total chars:), so every printed line maps back to its originating operation.
Statements that matter
String[] array = names.stream().toArray(String[]::new);
return s.toUpperCase();
List<StringBuilder> builders = names.stream()
.map(StringBuilder::new)
.toList();
FAQ
- What does Method References in Stream Pipelines print when run?
- Running the file directly is enough — expect labeled output lines such as `Sorted:`, `Array length:`, `Total chars:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.