Java 8 Lambda Expressions, Stream API, and Optional Tutorial
Java 8 adds powerful functional constructs—lambda expressions, method and constructor references, the Stream API, and Optional—plus a modern, thread‑safe date‑time library, and this tutorial explains their syntax, core interfaces, common operations, and practical backend examples to improve code readability and conciseness.
Java 8 introduces major language features such as Lambda expressions, the Stream API, Optional, and a new date‑time library. This article explains the syntax, usage patterns, and common functional interfaces, and demonstrates how to apply these features in typical backend development scenarios.
Lambda Expressions
A Lambda expression is an anonymous function that can be passed as a parameter. It simplifies code that previously required anonymous inner classes.
@Test
public void test() {
Comparator<Integer> comparator = (o1, o2) -> o2 - o1;
Set<Integer> set = new TreeSet<>(comparator);
set.add(3);
set.add(2);
set.add(1);
System.out.println(set);
}Lambda expressions rely on functional interfaces (interfaces with a single abstract method). The four core functional interfaces are Consumer, Supplier, Function, and Predicate.
Method References and Constructor References
Method references provide a concise way to refer to existing methods. Three forms exist: object::instanceMethod, Class::staticMethod, and Class::instanceMethod. Constructor references use Class::new.
Consumer<String> consumer = System.out::println;
Supplier<User> supplier = User::new;
Function<String, User> function = User::new;Stream API
Streams enable functional‑style operations on collections, such as filtering, mapping, sorting, and aggregation.
List<User> userList = Arrays.asList(
new User("张三", 20, 0),
new User("李四", 30, 0),
new User("王五", 25, 1),
new User("赵六", 42, 1)
);
// Filter users older than 25
Stream<User> stream = userList.stream()
.filter(user -> user.getAge() > 25);
stream.forEach(System.out::println);Common stream operations demonstrated include: filter – retain elements matching a predicate. map – transform each element. sorted – natural or custom ordering. limit / skip – pagination. distinct – remove duplicates (requires proper equals and hashCode). anyMatch, allMatch, noneMatch – boolean checks. findFirst, findAny – retrieve elements. count, max, min – aggregate values. reduce – combine elements to a single result. collect – gather results into collections, maps, or perform grouping/partitioning.
Optional
The Optional class is a container that may hold a non‑null value, helping to avoid NullPointerException. Common methods include of, ofNullable, isPresent, orElse, orElseGet, map, and flatMap.
Optional<User> optional = Optional.of(new User());
User user = optional.get();
boolean present = optional.isPresent();
User fallback = optional.orElse(new User("李四", 22, 0));
Optional<String> name = optional.map(User::getName);New Date‑Time API (java.time)
Classes such as LocalDate, LocalTime, LocalDateTime, and Instant are immutable and thread‑safe. Formatting and parsing use DateTimeFormatter. Time‑zone handling is provided by ZoneId and ZonedDateTime. Temporal adjusters ( TemporalAdjuster) simplify date calculations.
// Current date
LocalDate today = LocalDate.now();
// Specific date
LocalDate date = LocalDate.of(2021, 4, 10);
// Add one week
LocalDate nextWeek = today.plusWeeks(1);
// Format
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
String formatted = LocalDateTime.now().format(fmt);
// Parse
LocalDateTime parsed = LocalDateTime.parse(formatted, fmt);
// Instant with offset
Instant now = Instant.now();
OffsetDateTime odt = now.atOffset(ZoneOffset.ofHours(8));Overall, the article provides a comprehensive guide for Java developers to adopt Java 8 functional programming constructs and the modern date‑time API, improving code readability, conciseness, and thread safety.
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.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.
