☕ Modern Java LTS Features: From 8 to 21
Java has evolved significantly from version 8 through 21, introducing new language features, APIs, and performance improvements. This post highlights key features across LTS releases, with examples for each version. ๐
1. ๐ Java 8
Java 8 introduced major language and API enhancements, including streams, functional interfaces, and the Date/Time API.
- Streams: Creational, Intermediate, and Terminal operations for processing collections.
- Functional Interfaces: Single abstract method (Runnable, Comparator, Callable).
- Distinct vs Set: Remove duplicates in streams.
- Foreach: Terminal operation for iterating elements.
- Map / FlatMap: Transform and flatten collections.
Common Functional Interfaces:
- Predicate: VALUE → BOOLEAN (filter)
- Supplier: NOTHING → VALUE (generate)
- Consumer: VALUE → NOTHING (accept)
- Function: VALUE → VALUE (apply)
Method References: Use a method instead of a lambda expression for cleaner syntax.
2. ⚡ Java 11
Java 11, an LTS release, focused on productivity and performance improvements.
- String Methods:
isBlank()
,lines()
,strip()
,repeat()
. - Collection toArray: Type-safe conversion
list.toArray(String[]::new)
. - Local-Variable Syntax for Lambda: Use
var
in lambda parameters. - HTTP Client API: Modern, asynchronous HTTP requests.
- Flight Recorder & JFR Events: Monitor application performance.
3. ๐ Java 17
Java 17 (LTS) brings more modern features for safer and cleaner code.
Sealed Classes
Restrict which classes can extend a class/interface:
public sealed class Shape permits Circle, Rectangle { }
public final class Circle extends Shape { }
public final class Rectangle extends Shape { }
Pattern Matching for instanceof
Object obj = "Hello Java 17";
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}
Records
public record Person(String name, int age) { }
Person p = new Person("Alice", 25);
System.out.println(p.name());
Switch Expressions
String day = "MONDAY";
int numLetters = switch (day) {
case "MONDAY", "FRIDAY" -> 6;
case "TUESDAY" -> 7;
default -> throw new IllegalArgumentException("Unknown day: " + day);
};
Text Blocks
String json = """
{
"name": "Alice",
"age": 25
}
""";
4. ๐ Java 21 (enhanced examples)
Pattern Matching for switch
record Point(int x, int y) {}
Object obj = new Point(10, 20);
String result = switch (obj) {
case Point(int x, int y) p -> "Point at " + x + "," + y;
case String s -> "String: " + s;
default -> "Unknown type";
};
System.out.println(result); // Point at 10,20
Record Patterns & Nested Pattern Matching
record Rectangle(Point topLeft, Point bottomRight) {}
Object shape = new Rectangle(new Point(0,0), new Point(5,5));
String desc = switch (shape) {
case Rectangle(Point(int x1, int y1), Point(int x2, int y2)) r ->
"Rectangle from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")";
default -> "Unknown shape";
};
System.out.println(desc);
// Rectangle from (0,0) to (5,5)
Virtual Threads
// Lightweight threads for massive concurrency
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) {
executor.submit(() -> {
Thread.sleep(10);
System.out.println("Hello from virtual thread: " + Thread.currentThread());
return null;
});
}
}
Scoped Values
// Share immutable data safely across virtual threads
ScopedValue currentUser = ScopedValue.newInstance();
ScopedValue.where(currentUser, "Alice", () -> {
Runnable task = () -> System.out.println("User: " + currentUser.get());
new Thread(task).start();
});
Generics Inference Improvements
// Type arguments inferred automatically
List list = List.of("a", "b", "c");
Map> map = Map.of("letters", list); // no <> repetition needed
Pattern Matching + instanceof Enhancements
Object input = "Hello World";
if (input instanceof String s && s.length() > 5) {
System.out.println("Long string: " + s);
}
๐ Java LTS Versions Summary
Java Version | Key Features | Notes / Examples |
---|---|---|
8 | Streams, Lambda Expressions, Functional Interfaces, Date/Time API | Stream operations (map, filter, flatMap), Predicate/Supplier/Consumer/Function |
11 | New String methods, HTTP Client, Flight Recorder, var in lambdas | isBlank(), lines(), repeat(), list.toArray(String[]::new), async HTTP requests |
17 | Sealed Classes, Records, Pattern Matching (instanceof), Switch Expressions, Text Blocks | Sealed hierarchies, compact data classes, simplified type checks, multi-line strings |
21 | Pattern Matching for switch, Record Patterns, Virtual Threads, Scoped Values, Generics Improvements | Switch with patterns, nested record matching, high concurrency with virtual threads, safe shared values |
Conclusion
From Java 8 to 21, each LTS release added powerful language features, improved performance, and enhanced developer productivity. Learning these features helps you write cleaner, safer, and more maintainable Java code across modern applications.
Labels for this post: Java, LTS Features, Java 8, Java 11, Java 17, Java 21, Modern Java, Functional Programming, Streams, Concurrency
Comments
Post a Comment