Master Java Lambda Expressions: From Anonymous Classes to Streamlined Code
This article explains why Java introduced the seemingly odd lambda syntax, shows how lambdas replace verbose anonymous inner classes for loops, grouping and collection operations, introduces functional interfaces, and provides comprehensive code examples demonstrating creation, method references, sorting, filtering, and threading with lambdas.
When I first started programming in Java, I often wrote cumbersome code for loops, grouping, and collection merging, which became much simpler after learning lambda expressions. This article explains the origin of Java lambdas and why their syntax may look unusual.
Lambda expressions are essentially a concise way to implement anonymous inner classes. An anonymous inner class defines a method body directly within a method without declaring a separate subclass. Lambdas build on this by omitting the method signature (modifiers, return type, name, and parameters) and using the arrow operator -> to separate parameters from the body, e.g., (x, y) -> { … }. When the parameter type can be inferred, it may be omitted, and a single‑parameter lambda can drop the parentheses. If the body consists of a single statement, the braces and even the return keyword can be omitted.
Because lambdas are used with functional interfaces—interfaces that declare exactly one abstract method—Java provides many such interfaces in java.util.function, including Function, Consumer, Supplier, and Predicate. These interfaces use generics for input and output types, making them ideal for processing collections, testing conditions, or supplying values.
package com.zhengxing.demo.lambda;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* Lambda usage examples
*/
public class TestDemo {
public static void main(String[] args) {
System.out.println("1、lambda 表达式使用");
// 1. Simple lambda
NoParamHasReturn book = () -> new Book();
// 2. Method reference
NoParamHasReturn bookRef = Book::new;
bookRef.getBoook();
System.out.println("2、List 数据使用 Lambda 表达式比较大小");
List<Book> books = new ArrayList<>();
books.add(new Book("Java", new BigDecimal("123.3")));
books.add(new Book("Jva", new BigDecimal("123.5")));
books.add(new Book("Ja", new BigDecimal("123.1")));
System.out.println(books);
// Comparator with lambda
Comparator<Book> bookComparator = (a, b) -> a.price.compareTo(b.price);
books.sort(Comparator.comparing(b -> b.price));
System.out.println(books);
System.out.println("3、Set 数据自定义排序");
Set<Book> set = new TreeSet<>((x, y) -> x.price.compareTo(y.price));
set.addAll(books);
System.out.println(set);
System.out.println("4、List 数据 排序筛选");
List<Integer> data = Arrays.asList(1, 2, 46, 88, 45, 3);
data.forEach(System.out::println);
System.out.println("-----");
data.forEach(x -> { if (x > 10) System.out.println(x); });
System.out.println("-----");
List<Integer> filtered = data.stream()
.filter(x -> x > 10)
.collect(Collectors.toList());
System.out.println(filtered);
System.out.println("5、删除大于124 元的书");
List<Book> moreBooks = new ArrayList<>();
moreBooks.add(new Book("Java", new BigDecimal("125.3")));
moreBooks.add(new Book("Jva", new BigDecimal("123.5")));
moreBooks.add(new Book("Ja", new BigDecimal("123.1")));
moreBooks.removeIf(b -> b.price.compareTo(new BigDecimal("124")) > 0);
System.out.println(moreBooks);
System.out.println("6、使用 Lambda 调用线程");
new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.print(i + "、");
}
}).start();
}
}The code demonstrates creating lambdas, using method references, sorting lists and sets with custom comparators, filtering streams, removing elements based on a condition, and running a simple lambda in a new thread, illustrating how lambdas make Java code more concise and expressive.
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.
Lin is Dream
Sharing Java developer knowledge, practical articles, and continuous insights into computer engineering.
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.
