Java 8 Features
Java 8 was a landmark release that brought functional programming idioms into the language. The centerpiece is the lambda expression, a concise way to repr...
Lambda Expressions and Functional Interfaces
Java 8 was a landmark release that brought functional programming idioms into the language. The centerpiece is the lambda expression, a concise way to represent an anonymous function. Before Java 8, passing behavior meant creating anonymous inner classes — verbose blocks of boilerplate. A lambda collapses this to a parameter list, an arrow, and a body: (int a, int b) -> a + b.
Lambdas work because Java 8 formalized the concept of a functional interface — any interface with exactly one abstract method. The @FunctionalInterface annotation makes this contract explicit and triggers a compile error if you accidentally add a second abstract method. The java.util.function package ships with a rich set of ready-made functional interfaces. Predicate<T> tests a condition and returns boolean. Function<T, R> transforms a T into an R. Consumer<T> accepts a value and returns nothing (useful for side effects like printing). Supplier<T> takes no arguments and produces a T.
Method references are shorthand for lambdas that simply delegate to an existing method. System.out::println is equivalent to x -> System.out.println(x). You can reference static methods (Math::abs), instance methods on a particular object (myList::add), instance methods on an arbitrary instance of a type (String::toUpperCase), and constructors (ArrayList::new). Method references improve readability when the lambda body is nothing more than a single method call.
The Optional<T> class, also introduced in Java 8, models a value that may or may not be present without resorting to null. optional.map(String::toUpperCase).orElse("default") chains a transformation and supplies a fallback in one readable pipeline, eliminating a cascade of null checks. Optional is best used as a return type from methods, not as a field or parameter type.
One tip for beginners: start by replacing simple Comparator anonymous classes with lambdas. list.sort((a, b) -> a.getName().compareTo(b.getName())) is a natural first exercise that immediately shows the readability gain.
The Stream API
The Stream API is arguably the most transformative addition in Java 8. A Stream is a sequence of elements that supports a pipeline of operations — filtering, mapping, reducing — executed lazily and potentially in parallel with almost no extra code.
Streams come from collections (list.stream()), arrays (Arrays.stream(arr)), or factory methods (Stream.of("a", "b")). Operations divide into intermediate and terminal. Intermediate operations — filter, map, flatMap, sorted, distinct, limit — return a new Stream and do nothing until a terminal operation fires. Terminal operations — collect, forEach, reduce, count, findFirst, anyMatch — trigger the pipeline and produce a result or side effect.
A concrete example: given a list of Employee objects, finding the names of employees in the "Engineering" department earning above 80,000, sorted alphabetically, looks like this — list.stream().filter(e -> e.getDept().equals("Engineering")).filter(e -> e.getSalary() > 80000).map(Employee::getName).sorted().collect(Collectors.toList()). Each step is a declarative statement of intent, not an imperative loop.
The Collectors utility class provides powerful terminal aggregations. Collectors.groupingBy(Employee::getDept) produces a Map<String, List<Employee>> grouping employees by department. Collectors.joining(", ") concatenates strings. Collectors.toMap, Collectors.counting, and Collectors.summarizingInt cover most other aggregation needs.
Parallel streams split work across the common ForkJoinPool. Switching a pipeline to parallel is a single keyword change: list.parallelStream(). However, parallel streams are not always faster. For small lists, the overhead of splitting and merging outweighs the gains. Parallel streams also require that your operations be stateless and avoid shared mutable state; otherwise you risk race conditions. Benchmark before committing.
One practical tip: avoid using forEach for transformations. forEach is for side effects. If you find yourself calling forEach to build a result, you likely want map and collect instead.
Date/Time API and Default Methods
The legacy java.util.Date and java.util.Calendar classes were notoriously painful to use — mutable, poorly designed, and riddled with gotchas like months being zero-indexed. Java 8 replaced them with the java.time package, modeled on the Joda-Time library and designed by its author.
The new API centers on a handful of clear, immutable classes. LocalDate represents a calendar date without time or time zone — perfect for birthdays or deadlines. LocalTime represents a time of day. LocalDateTime combines both. ZonedDateTime adds a time zone for precise moment-in-time calculations across regions. Instant represents a point on the UTC timeline as an epoch-based timestamp, useful for logging and interoperability with legacy APIs.
Arithmetic is intuitive: LocalDate tomorrow = LocalDate.now().plusDays(1). Comparison is equally clean: date1.isBefore(date2). Parsing and formatting use DateTimeFormatter: LocalDate d = LocalDate.parse("2024-03-15", DateTimeFormatter.ISO_LOCAL_DATE). Custom patterns like DateTimeFormatter.ofPattern("dd/MM/yyyy") are common in user-facing applications. Because formatter instances are thread-safe, you can safely share them as static constants, unlike the old SimpleDateFormat.
Period measures date-based amounts (days, months, years). Duration measures time-based amounts (hours, minutes, seconds, nanoseconds). ChronoUnit provides a straightforward way to compute differences: ChronoUnit.DAYS.between(startDate, endDate).
Default methods, another Java 8 addition, allow interfaces to ship concrete method implementations. This was the mechanism that let Oracle add new methods — like forEach, stream, and spliterator — to the existing Collection interfaces without breaking every class that implemented them. You can add default methods to your own interfaces to provide sensible behavior that implementing classes inherit but can override. Static methods in interfaces arrived at the same time, enabling factory and utility methods to live alongside their interface rather than in a separate helper class.