Understanding Java 8 Functional Interfaces and Stream Operations

This article explains Java 8's lambda expressions, functional interfaces, and the Stream API, demonstrating how immutable values and functions enable concise data processing through lazy and eager evaluation, with practical code examples covering predicates, consumers, mapping, filtering, grouping, and reduction.

Architecture Digest
Architecture Digest
Architecture Digest
Understanding Java 8 Functional Interfaces and Stream Operations

Java 8 introduced lambda expressions and functional programming concepts, allowing behavior to be passed as immutable values and processed through functions, which makes code more expressive and concise.

A functional interface is an interface with a single abstract method, marked with @FunctionalInterface. It can also contain default and static methods. Common built‑in functional interfaces include Predicate, Consumer, Function, Supplier, UnaryOperator, and BinaryOperator.

Example code illustrating these interfaces:

public class Test {
    public static void main(String[] args) {
        Predicate<Integer> predicate = x -> x > 185;
        Student student = new Student("9龙", 23, 175);
        System.out.println("9龙的身高高于185吗?:" + predicate.test(student.getStature()));

        Consumer<String> consumer = System.out::println;
        consumer.accept("命运由我不由天");

        Function<Student, String> function = Student::getName;
        String name = function.apply(student);
        System.out.println(name);

        Supplier<Integer> supplier = () -> Integer.valueOf(BigDecimal.TEN.toString());
        System.out.println(supplier.get());

        UnaryOperator<Boolean> unaryOperator = uglily -> !uglily;
        Boolean apply2 = unaryOperator.apply(true);
        System.out.println(apply2);

        BinaryOperator<Integer> operator = (x, y) -> x * y;
        Integer integer = operator.apply(2, 3);
        System.out.println(integer);

        test(() -> "我是一个演示的函数式接口");
    }

    public static void test(Worker worker) {
        String work = worker.work();
        System.out.println(work);
    }

    public interface Worker {
        String work();
    }
}

The Stream API processes collections lazily (operations return another Stream) and evaluates eagerly when a terminal operation is invoked. Common stream operations demonstrated include:

collect(Collectors.toList()) – converts a Stream to a List.

filter – selects elements matching a Predicate.

map – transforms each element using a Function.

flatMap – flattens multiple Streams into one.

max / min – finds the maximum or minimum element using a Comparator, returning an Optional.

count – counts elements, often after a filter.

reduce – aggregates elements into a single value.

Example of filter and map:

List<Student> list = students.stream()
    .filter(stu -> stu.getStature() < 180)
    .collect(Collectors.toList());
System.out.println(list);

List<String> names = students.stream()
    .map(Student::getName)
    .collect(Collectors.toList());
System.out.println(names);

Advanced collectors such as partitioningBy, groupingBy, and joining enable complex data aggregation:

Map<Boolean, List<Student>> partitioned = students.stream()
    .collect(Collectors.partitioningBy(s -> s.getSpecialities().contains(SpecialityEnum.SING)));

Map<SpecialityEnum, List<Student>> grouped = students.stream()
    .collect(Collectors.groupingBy(s -> s.getSpecialities().get(0)));

String joined = students.stream()
    .map(Student::getName)
    .collect(Collectors.joining(",", "[", "]"));
System.out.println(joined);

The article concludes that Java 8 streams and lambda expressions provide a clear, concise way to manipulate collections, encouraging developers to refactor existing codebases to leverage functional programming features for better readability and maintainability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaLambdaStreamsjava8Functional InterfacesCollectors
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.