Java Developer Cheatsheet
A quick reference guide for modern Java (Java 8 to 21), covering core syntax, streams, lambdas, and common APIs.
1. Basics & Syntax
Hello World
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Data Types
- Primitives:
int(32-bit),long(64-bit),double(64-bit),float(32-bit),boolean,char,byte,short. - Wrappers:
Integer,Long,Double,Boolean, etc.
Switch Expressions (Java 12+)
String dayType = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> "Weekend";
default -> throw new IllegalArgumentException("Invalid day");
};
Records (Java 14+)
Concise syntax for immutable data carrier classes.
public record User(String name, int age) {}
User u = new User("Alice", 30);
System.out.println(u.name()); // "Alice"
Text Blocks (Java 15+)
Multi-line string literals.
String json = """
{
"name": "John",
"age": 30
}
""";
2. Collections Framework
Initialization
// Java 9+ Factory methods (Immutable)
List<String> list = List.of("A", "B", "C");
Set<Integer> set = Set.of(1, 2, 3);
Map<String, Integer> map = Map.of("A", 1, "B", 2);
// Mutable initialization
List<String> mutableList = new ArrayList<>(Arrays.asList("A", "B"));
Map Iteration
Map<String, Integer> map = new HashMap<>();
map.forEach((key, value) -> System.out.println(key + ":" + value));
3. Lambdas & Functional Interfaces (Java 8+)
Common Functional Interfaces (java.util.function)
Predicate<T>: TakesT, returnsboolean.Function<T, R>: TakesT, returnsR.Consumer<T>: TakesT, returnsvoid.Supplier<T>: Takes nothing, returnsT.
Lambda Syntax
// No arguments
Runnable r = () -> System.out.println("Run");
// Single argument
Consumer<String> c = s -> System.out.println(s);
// Multiple arguments
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
4. Streams API (Java 8+)
Streams allow declarative processing of collections.
Creation
Stream<String> s1 = list.stream();
Stream<Integer> s2 = Stream.of(1, 2, 3);
IntStream s3 = IntStream.range(1, 10); // 1 to 9
Intermediate Operations (Lazy)
filter(Predicate): Filters elements.map(Function): Transforms elements.flatMap(Function): Flattens nested structures.distinct(): Removes duplicates.sorted(): Sorts elements.limit(n): Truncates stream tonelements.
Terminal Operations (Trigger execution)
collect(Collector): Gathers elements (e.g.,Collectors.toList()).- Java 16+: can just use
stream.toList()
- Java 16+: can just use
forEach(Consumer): Iterates elements.reduce(BinaryOperator): Combines elements.anyMatch(Predicate),allMatch,noneMatch: Returns boolean.findFirst(),findAny(): ReturnsOptional.
Stream Examples
// Filter and map
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.toList(); // .collect(Collectors.toList()) in pre-Java 16
// Grouping By
Map<Integer, List<String>> byLength = names.stream()
.collect(Collectors.groupingBy(String::length));
5. Optionals
Avoid NullPointerException.
Optional<String> opt = Optional.ofNullable(getValue());
// Safe execution
opt.ifPresent(val -> System.out.println(val));
// Fallbacks
String val1 = opt.orElse("Default");
String val2 = opt.orElseGet(() -> computeDefault());
String val3 = opt.orElseThrow(() -> new RuntimeException("Not found"));
6. Date & Time API (Java 8+ java.time)
Immutable date/time objects.
LocalDate date = LocalDate.now();
LocalDate specific = LocalDate.of(2023, Month.OCTOBER, 31);
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
// Parsing & Formatting
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formatted = date.format(formatter);
LocalDate parsed = LocalDate.parse("31/10/2023", formatter);