Java 8 Functional Interfaces and Stream Operations: A Comprehensive Guide
This article explains Java 8's lambda expressions and functional interfaces, demonstrates common functional interfaces with code examples, and shows how to use Stream API operations such as filter, map, flatMap, collect, max/min, count, reduce, and advanced collectors for efficient backend development.
Java 8 introduced lambda expressions, bringing functional programming to the language and allowing behavior to be passed as immutable values.
A functional interface is an interface that contains only one abstract method and can be annotated with @FunctionalInterface. The article defines several built‑in functional interfaces (Predicate, Consumer, Function, Supplier, UnaryOperator, BinaryOperator) and a custom interface, showing how they are used with lambda expressions.
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(() -> "我是一个演示的函数式接口");
}
/**
* Demonstrates a custom functional interface usage
*/
public static void test(Worker worker) {
String work = worker.work();
System.out.println(work);
}
public interface Worker {
String work();
}
}
//9龙的身高高于185吗:false
//命运由我不由天
//9龙
//10
//false
//6
//我是一个演示的函数式接口The article then introduces the Stream API, explaining lazy and eager evaluation and providing concrete examples for common operations:
collect(Collectors.toList()) : converts a stream to a list.
filter : uses a Predicate to keep elements that satisfy a condition.
map : transforms each element, e.g., extracting student names.
flatMap : merges multiple streams into one.
max / min : finds the maximum or minimum element using a Comparator, returning an Optional.
count : counts elements after optional filtering.
reduce : aggregates values, such as summing integers.
public class TestCase {
public static void main(String[] args) {
List<Student> studentList = Stream.of(
new Student("路飞", 22, 175),
new Student("红发", 40, 180),
new Student("白胡子", 50, 185))
.collect(Collectors.toList());
System.out.println(studentList);
}
}
//[Student{name='路飞', age=22, stature=175}, Student{name='红发', age=40, stature=180}, Student{name='白胡子', age=50, stature=185}]Advanced collectors are also covered, including partitioningBy to split a collection into two groups based on a predicate, groupingBy for arbitrary grouping, and joining for concatenating strings with optional delimiters, prefixes, and suffixes.
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 names = students.stream()
.map(Student::getName)
.collect(Collectors.joining(",", "[", "]"));
System.out.println(names); // [路飞,红发,白胡子]In the conclusion, the author emphasizes that Java 8 streams enable concise, expressive code for processing collections and encourages readers to refactor existing codebases to take advantage of these features.
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.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.
