Method References in Stream Pipelines

Demonstrates four types of method references (static, instance, arbitrary object, constructor) to create concise and readable functional expressions.

JavaData Fetching

Code

snippet
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);
    }
}