Quick Reference Cheat Sheet¶
A scannable reference for all major features. Perfect for last-minute review.
Java 8 (2014) - Functional Programming¶
Lambda Expressions¶
// Syntax variations
() -> expression // No parameters
x -> expression // Single parameter
(x, y) -> expression // Multiple parameters
(x, y) -> { statements; return z; } // Block body
Stream API¶
list.stream()
.filter(x -> x > 0) // Intermediate
.map(x -> x * 2) // Intermediate
.sorted() // Intermediate
.distinct() // Intermediate
.limit(10) // Intermediate
.collect(Collectors.toList()); // Terminal
// Parallel
list.parallelStream().filter(...).collect(...);
Optional¶
Optional.of(value) // Non-null value
Optional.ofNullable(value) // May be null
Optional.empty() // Empty optional
opt.map(v -> transform(v)) // Transform if present
opt.flatMap(v -> optionalResult) // Flatten nested Optional
opt.filter(v -> condition) // Filter
opt.orElse(default) // Get or default
opt.orElseGet(() -> compute()) // Get or compute
opt.orElseThrow(() -> ex) // Get or throw
opt.ifPresent(v -> use(v)) // Execute if present
Method References¶
Math::abs // Static method
String::toUpperCase // Instance method (unbound)
myObj::process // Instance method (bound)
Person::new // Constructor
Date/Time¶
LocalDate.now()
LocalDate.of(2024, 1, 15)
LocalDateTime.now()
ZonedDateTime.now(ZoneId.of("UTC"))
date.plusDays(1)
Duration.between(start, end)
Period.between(startDate, endDate)
Java 11 (2018) - Modernization¶
var Keyword¶
var list = new ArrayList<String>(); // ArrayList<String>
var map = Map.of("a", 1); // Map<String, Integer>
var stream = list.stream(); // Stream<String>
// In lambdas (with annotations)
list.forEach((@NotNull var s) -> process(s));
HTTP Client¶
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com"))
.header("Accept", "application/json")
.GET() // or .POST(BodyPublishers.ofString(body))
.build();
// Sync
HttpResponse<String> response = client.send(
request, BodyHandlers.ofString());
// Async
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
String Methods¶
" text ".strip() // "text" (Unicode-aware)
" ".isBlank() // true
"a\nb\nc".lines() // Stream<String>
"ab".repeat(3) // "ababab"
" hi ".stripLeading() // "hi "
" hi ".stripTrailing() // " hi"
Files¶
String content = Files.readString(Path.of("file.txt"));
Files.writeString(Path.of("file.txt"), content);
Collections¶
List.of("a", "b", "c") // Immutable list
Set.of(1, 2, 3) // Immutable set
Map.of("a", 1, "b", 2) // Immutable map
Map.ofEntries(entry("a", 1)) // For >10 entries
Java 17 (2021) - Type Safety¶
Records¶
public record Person(String name, int age) { }
// With validation
public record Person(String name, int age) {
public Person { // Compact constructor
if (age < 0) throw new IllegalArgumentException();
}
}
// Usage
var p = new Person("Alice", 30);
p.name() // "Alice"
p.age() // 30
Sealed Classes¶
public sealed interface Shape permits Circle, Square { }
public final class Circle implements Shape { }
public final class Square implements Shape { }
public non-sealed class Triangle implements Shape { } // Allows extension
Pattern Matching instanceof¶
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}
if (obj instanceof String s && s.length() > 5) {
// s in scope and condition checked
}
Text Blocks¶
String json = """
{
"name": "Alice",
"age": 30
}
""";
// With formatting
String template = """
Hello %s,
Welcome!
""".formatted(name);
Switch Expressions¶
int result = switch (day) {
case MONDAY, FRIDAY -> 1;
case TUESDAY -> 2;
default -> {
log("other day");
yield 0; // yield for blocks
}
};
Java 21 (2023) - Concurrency Revolution¶
Virtual Threads¶
// Executor (recommended)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> handleRequest());
}
// Direct creation
Thread.startVirtualThread(() -> doWork());
Thread.ofVirtual().name("my-vt").start(() -> doWork());
// Check if virtual
Thread.currentThread().isVirtual()
Pattern Matching for switch¶
String result = switch (obj) {
case null -> "null";
case String s when s.isEmpty() -> "empty string";
case String s -> "string: " + s;
case Integer i -> "int: " + i;
case List<?> list when list.size() > 10 -> "big list";
default -> "other";
};
Record Patterns¶
record Point(int x, int y) { }
if (obj instanceof Point(int x, int y)) {
System.out.println(x + ", " + y);
}
// Nested
record Line(Point start, Point end) { }
if (obj instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) {
// Direct access to x1, y1, x2, y2
}
Sequenced Collections¶
SequencedCollection<String> coll = list;
coll.getFirst()
coll.getLast()
coll.addFirst(element)
coll.addLast(element)
coll.removeFirst()
coll.removeLast()
coll.reversed()
// SequencedMap
map.firstEntry()
map.lastEntry()
map.putFirst(k, v)
map.reversed()
Java 25 (2025) - Refinements¶
Primitive Type Patterns¶
switch (value) {
case int i when i > 0 -> "positive int";
case int i -> "non-positive int";
case double d -> "double";
default -> "other";
}
Flexible Constructor Bodies¶
public MyClass(String input) {
// Validation BEFORE super() now allowed
if (input == null) throw new IllegalArgumentException();
var processed = input.trim();
super(processed); // Can be after validation
this.value = processed;
}
Compact Source Files¶
Scoped Values¶
private static final ScopedValue<User> USER = ScopedValue.newInstance();
// Set and use
ScopedValue.where(USER, currentUser).run(() -> {
processRequest(); // USER.get() works here
});
// In nested calls
User user = USER.get(); // Get value
boolean bound = USER.isBound(); // Check if set
Quick Comparison Table¶
| Feature | Java 8 | 11 | 17 | 21 | 25 |
|---|---|---|---|---|---|
| Lambdas | |||||
| Streams | |||||
| var | |||||
| Records | |||||
| Sealed | |||||
| Virtual Threads | |||||
| Pattern switch | |||||
| Scoped Values |