Java Cheatsheet

Quick reference for Java 8+ features and syntax

Java 8+
Streams & Lambda
Collections

Java 8+ Quick Reference

This cheatsheet covers the most commonly used Java 8+ features including streams, lambda expressions, collections, and modern Java syntax. Perfect for quick reference during development.

Basic Syntax

Class Declaration

Basic class structure with constructor and getter

public class MyClass {
    private String name;
    
    public MyClass(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

Main Method

Entry point for Java applications

public static void main(String[] args) {
    System.out.println("Hello, World!");
}

Variable Declaration

Different ways to declare variables

// Primitive types
int number = 42;
double decimal = 3.14;
boolean flag = true;
String text = "Hello";

// Final (immutable)
final int CONSTANT = 100;

// Var (Java 10+)
var message = "Type inference";

Collections

List Operations

Common List operations and immutable lists

List<String> list = new ArrayList<>();
list.add("item");
list.add(0, "first");
list.remove("item");
list.size();
list.isEmpty();
list.contains("item");

// Java 9+ List.of()
List<String> immutableList = List.of("a", "b", "c");

Map Operations

Map operations and immutable maps

Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
map.get("key");
map.containsKey("key");
map.remove("key");
map.size();

// Java 9+ Map.of()
Map<String, Integer> immutableMap = Map.of("a", 1, "b", 2);

Set Operations

Set operations and immutable sets

Set<String> set = new HashSet<>();
set.add("item");
set.remove("item");
set.contains("item");
set.size();

// Java 9+ Set.of()
Set<String> immutableSet = Set.of("a", "b", "c");

Streams (Java 8+)

Basic Stream Operations

Common stream operations: filter, map, reduce

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Filter
names.stream()
    .filter(name -> name.startsWith("A"))
    .forEach(System.out::println);

// Map
names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

// Reduce
int totalLength = names.stream()
    .mapToInt(String::length)
    .sum();

Collectors

Different collectors for stream results

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// To List
List<String> list = names.stream()
    .collect(Collectors.toList());

// To Set
Set<String> set = names.stream()
    .collect(Collectors.toSet());

// To Map
Map<String, Integer> map = names.stream()
    .collect(Collectors.toMap(
        name -> name,
        String::length
    ));

// Joining
String joined = names.stream()
    .collect(Collectors.joining(", "));

Parallel Streams

Parallel stream processing for performance

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Parallel processing
names.parallelStream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

// With custom thread pool
ForkJoinPool customThreadPool = new ForkJoinPool(4);
customThreadPool.submit(() ->
    names.parallelStream()
        .map(String::toUpperCase)
        .collect(Collectors.toList())
).get();

Lambda Expressions

Basic Lambda Syntax

Different lambda expression syntax patterns

// Single parameter
names.forEach(name -> System.out.println(name));

// Multiple parameters
list.sort((a, b) -> a.compareTo(b));

// No parameters
Supplier<String> supplier = () -> "Hello";

// Multiple statements
names.forEach(name -> {
    String upper = name.toUpperCase();
    System.out.println(upper);
});

Method References

Method reference syntax for cleaner code

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Static method reference
names.forEach(System.out::println);

// Instance method reference
names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

// Constructor reference
names.stream()
    .map(Person::new)
    .collect(Collectors.toList());

Optional (Java 8+)

Optional Basics

Optional class for null-safe operations

// Creating Optional
Optional<String> optional = Optional.of("value");
Optional<String> empty = Optional.empty();
Optional<String> nullable = Optional.ofNullable(null);

// Checking and getting
if (optional.isPresent()) {
    String value = optional.get();
}

// Safe operations
String result = optional.orElse("default");
String result2 = optional.orElseGet(() -> "computed");
optional.orElseThrow(() -> new RuntimeException("Not found"));

// Functional style
optional.ifPresent(System.out::println);
optional.map(String::toUpperCase).orElse("DEFAULT");

Date/Time API (Java 8+)

LocalDate and LocalTime

Modern date/time API usage

// Current date/time
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();

// Creating specific dates
LocalDate date = LocalDate.of(2023, 12, 25);
LocalTime time = LocalTime.of(14, 30, 0);

// Parsing
LocalDate parsed = LocalDate.parse("2023-12-25");
LocalTime parsedTime = LocalTime.parse("14:30:00");

// Manipulation
LocalDate tomorrow = today.plusDays(1);
LocalDate nextMonth = today.plusMonths(1);
LocalTime later = now.plusHours(2);

Duration and Period

Duration and Period for time calculations

// Duration (time-based)
Duration duration = Duration.ofHours(2);
Duration between = Duration.between(startTime, endTime);

// Period (date-based)
Period period = Period.ofDays(7);
Period betweenDates = Period.between(startDate, endDate);

// Adding to date/time
LocalDateTime future = dateTime.plus(duration);
LocalDate futureDate = date.plus(period);

Exception Handling

Try-Catch Blocks

Basic exception handling with try-catch-finally

try {
    // Risky code
    File file = new File("nonexistent.txt");
    Scanner scanner = new Scanner(file);
} catch (FileNotFoundException e) {
    // Handle specific exception
    System.err.println("File not found: " + e.getMessage());
} catch (Exception e) {
    // Handle any other exception
    System.err.println("Unexpected error: " + e.getMessage());
} finally {
    // Always executed
    System.out.println("Cleanup code");
}

Try-With-Resources (Java 7+)

Automatic resource management

// Automatic resource management
try (FileInputStream fis = new FileInputStream("file.txt");
     BufferedReader br = new BufferedReader(new InputStreamReader(fis))) {
    String line = br.readLine();
    System.out.println(line);
} catch (IOException e) {
    System.err.println("Error reading file: " + e.getMessage());
}

Need More Java Resources?

Explore our comprehensive Java documentation with detailed examples and explanations.