Code Snippets

This page is a quick-reference collection of commonly needed Java code snippets. Every snippet is self-contained, includes required imports, and shows expected output in comments. Copy, paste, adapt, and ship.

Snippets use modern Java where appropriate (Java 8+ Streams, Java 11+ HttpClient, java.time API).

String Operations

1. Reverse a String

String original = "Hello, World!";
String reversed = new StringBuilder(original).reverse().toString();
System.out.println(reversed); // !dlroW ,olleH

2. Check If a String Is a Palindrome

Compare the string with its reverse after normalizing case and stripping non-alphanumeric characters.

String input = "A man, a plan, a canal: Panama";
String cleaned = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
boolean isPalindrome = cleaned.equals(new StringBuilder(cleaned).reverse().toString());
System.out.println(isPalindrome); // true

3. Count Character Occurrences

String text = "mississippi";
char target = 's';
long count = text.chars().filter(c -> c == target).count();
System.out.println("'" + target + "' appears " + count + " times"); // 's' appears 4 times

4. Remove Whitespace

String padded = "  Hello   World  ";

// Remove ALL whitespace
String noSpaces = padded.replaceAll("\\s+", "");
System.out.println(noSpaces); // HelloWorld

// Remove only leading and trailing (Java 11+)
String stripped = padded.strip();
System.out.println("[" + stripped + "]"); // [Hello   World]

// trim() works on Java 8 but only removes ASCII spaces
String trimmed = padded.trim();
System.out.println("[" + trimmed + "]"); // [Hello   World]

5. Convert to Title Case

import java.util.Arrays;
import java.util.stream.Collectors;

String input = "the quick brown fox";
String titleCase = Arrays.stream(input.split("\\s+"))
    .map(w -> Character.toUpperCase(w.charAt(0)) + w.substring(1).toLowerCase())
    .collect(Collectors.joining(" "));
System.out.println(titleCase); // The Quick Brown Fox

6. Check If String Contains Only Digits or Letters

String digits = "123456";
String letters = "abcDEF";

// Regex approach
System.out.println(digits.matches("\\d+"));       // true (digits only)
System.out.println(letters.matches("[a-zA-Z]+")); // true (letters only)

// Character utility approach
boolean allDigits = digits.chars().allMatch(Character::isDigit);
boolean allLetters = letters.chars().allMatch(Character::isLetter);
System.out.println(allDigits + ", " + allLetters); // true, true

7. Split and Join Strings

import java.util.Arrays;
import java.util.stream.Collectors;

String csv = "apple,banana,cherry";
String[] fruits = csv.split(",");
System.out.println(Arrays.toString(fruits)); // [apple, banana, cherry]

String joined = String.join(" | ", fruits);
System.out.println(joined); // apple | banana | cherry

String streamed = Arrays.stream(fruits)
    .collect(Collectors.joining(", ", "[", "]"));
System.out.println(streamed); // [apple, banana, cherry]

8. String to int/double and Back

// String -> number
int num = Integer.parseInt("42");
double price = Double.parseDouble("19.99");

// Number -> String
String numStr = String.valueOf(num);          // "42"
String formatted = String.format("%.2f", price); // "19.99"

System.out.println(num + 1);   // 43
System.out.println(formatted); // 19.99

Array Operations

9. Sort an Array (Ascending and Descending)

import java.util.Arrays;
import java.util.Collections;

// Ascending (primitives)
int[] numbers = {5, 2, 8, 1, 9, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [1, 2, 3, 5, 8, 9]

// Descending (requires wrapper type)
Integer[] nums = {5, 2, 8, 1, 9, 3};
Arrays.sort(nums, Collections.reverseOrder());
System.out.println(Arrays.toString(nums)); // [9, 8, 5, 3, 2, 1]

10. Find Min/Max in an Array

import java.util.Arrays;

int[] numbers = {5, 2, 8, 1, 9, 3};
int max = Arrays.stream(numbers).max().orElseThrow();
int min = Arrays.stream(numbers).min().orElseThrow();
System.out.println("Max: " + max + ", Min: " + min); // Max: 9, Min: 1

11. Remove Duplicates from an Array

import java.util.*;

int[] numbers = {1, 3, 5, 3, 1, 7, 5, 9};
int[] unique = Arrays.stream(numbers).distinct().toArray();
System.out.println(Arrays.toString(unique)); // [1, 3, 5, 7, 9]

String[] words = {"apple", "banana", "apple", "cherry"};
var uniqueWords = new LinkedHashSet<>(Arrays.asList(words));
System.out.println(uniqueWords); // [apple, banana, cherry]

12. Merge Two Arrays

import java.util.Arrays;
import java.util.stream.IntStream;

int[] a = {1, 2, 3}, b = {4, 5, 6};

// System.arraycopy
int[] merged = new int[a.length + b.length];
System.arraycopy(a, 0, merged, 0, a.length);
System.arraycopy(b, 0, merged, a.length, b.length);
System.out.println(Arrays.toString(merged)); // [1, 2, 3, 4, 5, 6]

// Stream approach
int[] merged2 = IntStream.concat(IntStream.of(a), IntStream.of(b)).toArray();

13. Reverse an Array

int[] nums = {1, 2, 3, 4, 5};
for (int i = 0; i < nums.length / 2; i++) {
    int temp = nums[i];
    nums[i] = nums[nums.length - 1 - i];
    nums[nums.length - 1 - i] = temp;
}
System.out.println(java.util.Arrays.toString(nums)); // [5, 4, 3, 2, 1]

14. Binary Search

The array must be sorted before calling Arrays.binarySearch().

import java.util.Arrays;

int[] sorted = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int index = Arrays.binarySearch(sorted, 23);
System.out.println("Found 23 at index: " + index); // Found 23 at index: 5

int notFound = Arrays.binarySearch(sorted, 10);
System.out.println("10 result: " + notFound); // negative value (not found)

Collection Operations

15. Sort a List of Objects by Field

Use Comparator.comparing() for clean, readable sorting.

import java.util.*;

record Employee(String name, int age, double salary) {}

List emps = new ArrayList<>(List.of(
    new Employee("Alice", 30, 75000),
    new Employee("Bob", 25, 60000),
    new Employee("Charlie", 35, 90000)
));

emps.sort(Comparator.comparingInt(Employee::age));                // by age asc
emps.sort(Comparator.comparingDouble(Employee::salary).reversed()); // by salary desc
emps.sort(Comparator.comparing(Employee::name)
    .thenComparingInt(Employee::age));                             // by name, then age

emps.forEach(e -> System.out.println(e.name() + ": " + e.salary()));

16. Filter a List with Streams

import java.util.List;
import java.util.stream.Collectors;

List names = List.of("Alice", "Bob", "Amanda", "Charlie", "Andrea");

List aNames = names.stream()
    .filter(name -> name.startsWith("A"))
    .collect(Collectors.toList());
System.out.println(aNames); // [Alice, Amanda, Andrea]

List numbers = List.of(12, 55, 3, 89, 42, 67, 8);
List big = numbers.stream().filter(n -> n > 50).collect(Collectors.toList());
System.out.println(big); // [55, 89, 67]

17. Group Elements (Collectors.groupingBy)

import java.util.*;
import java.util.stream.Collectors;

record Product(String name, String category, double price) {}

List products = List.of(
    new Product("Laptop", "Electronics", 999.99),
    new Product("Phone", "Electronics", 699.99),
    new Product("Shirt", "Clothing", 29.99)
);

Map> byCategory = products.stream()
    .collect(Collectors.groupingBy(Product::category));

Map counts = products.stream()
    .collect(Collectors.groupingBy(Product::category, Collectors.counting()));
System.out.println(counts); // {Electronics=2, Clothing=1}

18. Convert List to Map

import java.util.*;
import java.util.stream.Collectors;

record User(int id, String name) {}

List users = List.of(new User(1, "Alice"), new User(2, "Bob"), new User(3, "Charlie"));

Map idToName = users.stream()
    .collect(Collectors.toMap(User::id, User::name));
System.out.println(idToName); // {1=Alice, 2=Bob, 3=Charlie}

// Handle duplicate keys with a merge function
List words = List.of("apple", "banana", "avocado");
Map byLetter = words.stream()
    .collect(Collectors.toMap(w -> w.charAt(0), w -> w,
        (old, nw) -> old + ", " + nw));
System.out.println(byLetter); // {a=apple, avocado, b=banana}

19. Find Duplicates in a List

import java.util.*;
import java.util.stream.Collectors;

List items = List.of("apple", "banana", "apple", "cherry", "banana");

Set seen = new HashSet<>();
Set duplicates = items.stream()
    .filter(item -> !seen.add(item)).collect(Collectors.toSet());
System.out.println(duplicates); // [banana, apple]

20. Merge Two Maps

import java.util.*;

Map map1 = new HashMap<>(Map.of("a", 1, "b", 2, "c", 3));
Map map2 = new HashMap<>(Map.of("b", 20, "c", 30, "d", 40));

// Simple merge (map2 overwrites on conflict)
Map merged = new HashMap<>(map1);
merged.putAll(map2);
System.out.println(merged); // {a=1, b=20, c=30, d=40}

// Merge with conflict resolution (sum values)
Map summed = new HashMap<>(map1);
map2.forEach((key, value) -> summed.merge(key, value, Integer::sum));
System.out.println(summed); // {a=1, b=22, c=33, d=40}

File I/O

21. Read a File Line by Line

import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Stream;

// Stream approach (auto-closes the file)
try (Stream lines = Files.lines(Path.of("data.txt"))) {
    lines.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

// Read all lines into a List
List allLines = Files.readAllLines(Path.of("data.txt"));

22. Write to a File

import java.nio.file.*;
import java.util.List;

// Write a string (Java 11+) -- creates or overwrites
Files.writeString(Path.of("output.txt"), "Hello, World!\n");

// Append to a file
Files.writeString(Path.of("output.txt"), "Appended line\n", StandardOpenOption.APPEND);

// Write multiple lines
List lines = List.of("Line 1", "Line 2", "Line 3");
Files.write(Path.of("lines.txt"), lines);

23. Read Entire File as String (Java 11+)

import java.nio.file.*;

// Java 11+
String content = Files.readString(Path.of("config.json"));
System.out.println(content);

// Java 8 alternative
String content8 = new String(Files.readAllBytes(Path.of("config.json")));

24. List Files in a Directory

import java.nio.file.*;

// List files (non-recursive)
try (var paths = Files.list(Path.of("."))) {
    paths.filter(Files::isRegularFile).forEach(System.out::println);
}

// Recursively find all .java files
try (var paths = Files.walk(Path.of("src"))) {
    paths.filter(p -> p.toString().endsWith(".java")).forEach(System.out::println);
}

25. Copy and Move Files

import java.nio.file.*;

Path source = Path.of("original.txt");

// Copy (overwrite if exists)
Files.copy(source, Path.of("backup.txt"), StandardCopyOption.REPLACE_EXISTING);

// Move (rename)
Files.move(source, Path.of("renamed.txt"), StandardCopyOption.REPLACE_EXISTING);

// Delete
Files.deleteIfExists(Path.of("temp.txt"));

Date and Time (Java 8+)

All date/time snippets use the java.time API. Avoid the legacy java.util.Date and SimpleDateFormat in new code.

26. Get Current Date and Time

import java.time.*;

LocalDate today = LocalDate.now();            // 2026-02-28
LocalTime now = LocalTime.now();              // 14:30:15.123
LocalDateTime dateTime = LocalDateTime.now(); // 2026-02-28T14:30:15
Instant instant = Instant.now();              // UTC timestamp
ZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("America/New_York"));

27. Format Date to String

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

LocalDateTime now = LocalDateTime.now();

DateTimeFormatter custom = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
System.out.println(now.format(custom)); // 02/28/2026 14:30:15

DateTimeFormatter readable = DateTimeFormatter.ofPattern("EEEE, MMMM d, yyyy");
System.out.println(now.format(readable)); // Saturday, February 28, 2026

28. Parse String to Date

import java.time.*;
import java.time.format.DateTimeFormatter;

LocalDate date = LocalDate.parse("2026-02-28"); // ISO format (default)

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate customDate = LocalDate.parse("02/28/2026", fmt);

DateTimeFormatter dtFmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse("2026-02-28 14:30:00", dtFmt);

29. Calculate Days Between Dates

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

LocalDate start = LocalDate.of(2026, 1, 1);
LocalDate end = LocalDate.of(2026, 12, 31);

long days = ChronoUnit.DAYS.between(start, end);
System.out.println("Days between: " + days); // 364

long months = ChronoUnit.MONTHS.between(start, end);
System.out.println("Months between: " + months); // 11

30. Add/Subtract Days from a Date

LocalDate is immutable -- every operation returns a new instance.

import java.time.LocalDate;

LocalDate today = LocalDate.now();
System.out.println("Next week:  " + today.plusDays(7));
System.out.println("Last month: " + today.minusMonths(1));
System.out.println("Next year:  " + today.plusYears(1));

// Chain operations
LocalDate future = today.plusYears(1).plusMonths(3).plusDays(10);

Map Operations

31. Iterate Over a Map

Map scores = Map.of("Alice", 95, "Bob", 87, "Charlie", 92);

// forEach with lambda (cleanest)
scores.forEach((name, score) -> System.out.println(name + ": " + score));

// entrySet with for-each loop
for (Map.Entry entry : scores.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

// Keys only / values only
scores.keySet().forEach(k -> System.out.println("Key: " + k));

32. Sort a Map by Value

Collect into a LinkedHashMap to preserve insertion order after sorting.

import java.util.*;
import java.util.stream.Collectors;

Map scores = Map.of("Alice", 95, "Bob", 87, "Charlie", 92);

// Sort by value ascending, collect into LinkedHashMap to preserve order
Map sorted = scores.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
        (e1, e2) -> e1, LinkedHashMap::new));
System.out.println(sorted); // {Bob=87, Charlie=92, Alice=95}

// Sort by value descending
Map desc = scores.entrySet().stream()
    .sorted(Map.Entry.comparingByValue().reversed())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
        (e1, e2) -> e1, LinkedHashMap::new));
System.out.println(desc); // {Alice=95, Charlie=92, Bob=87}

33. Merge Maps with Streams

import java.util.*;
import java.util.stream.*;

Map map1 = Map.of("a", 1, "b", 2);
Map map2 = Map.of("b", 3, "c", 4);
Map map3 = Map.of("c", 5, "d", 6);

Map merged = Stream.of(map1, map2, map3)
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
        (v1, v2) -> v2)); // on conflict, keep latest
System.out.println(merged); // {a=1, b=3, c=5, d=6}

34. Count Word Frequency

import java.util.*;
import java.util.stream.Collectors;

String text = "the quick brown fox jumps over the lazy dog the fox";

Map frequency = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
System.out.println(frequency); // {the=3, fox=2, quick=1, ...}

// Top 3 most frequent
frequency.entrySet().stream()
    .sorted(Map.Entry.comparingByValue().reversed())
    .limit(3).forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));

Math and Numbers

35. Generate Random Numbers (Range)

import java.util.concurrent.ThreadLocalRandom;

// Random int between 1 and 100 (inclusive)
int rand = ThreadLocalRandom.current().nextInt(1, 101);

// Dice roll (1 to 6)
int dice = (int) (Math.random() * 6) + 1;

// Stream of 5 random ints between 10 and 49
int[] randoms = new java.util.Random().ints(5, 10, 50).toArray();
System.out.println(java.util.Arrays.toString(randoms));

36. Round to N Decimal Places

import java.math.BigDecimal;
import java.math.RoundingMode;

double value = 3.14159265;

// BigDecimal (exact)
double rounded = BigDecimal.valueOf(value)
    .setScale(2, RoundingMode.HALF_UP).doubleValue();
System.out.println(rounded); // 3.14

// String.format (display only)
System.out.println(String.format("%.3f", value)); // 3.142

// Math.round trick
double rounded2 = Math.round(value * 100.0) / 100.0;
System.out.println(rounded2); // 3.14

37. Check If a Number Is Prime

public static boolean isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) return false;
    }
    return true;
}

System.out.println(isPrime(17));  // true
System.out.println(isPrime(100)); // false

// Find all primes up to 50
IntStream.rangeClosed(2, 50).filter(n -> isPrime(n))
    .forEach(n -> System.out.print(n + " "));
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

38. Calculate Factorial

import java.math.BigInteger;
import java.util.stream.LongStream;

// Iterative
public static long factorial(int n) {
    long result = 1;
    for (int i = 2; i <= n; i++) result *= i;
    return result;
}

// Stream approach
public static long factorialStream(int n) {
    return LongStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b);
}

// BigInteger for large values (no overflow)
public static BigInteger factorialBig(int n) {
    BigInteger r = BigInteger.ONE;
    for (int i = 2; i <= n; i++) r = r.multiply(BigInteger.valueOf(i));
    return r;
}

System.out.println(factorial(10));    // 3628800
System.out.println(factorialBig(50)); // 30414093201713378043...

39. Fibonacci Sequence

import java.util.stream.Stream;

public static long[] fibonacci(int n) {
    long[] fib = new long[n];
    fib[0] = 0; if (n > 1) fib[1] = 1;
    for (int i = 2; i < n; i++) fib[i] = fib[i - 1] + fib[i - 2];
    return fib;
}

System.out.println(java.util.Arrays.toString(fibonacci(10)));
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

// Infinite stream (take first 15)
Stream.iterate(new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]})
    .limit(15).map(f -> f[0]).forEach(n -> System.out.print(n + " "));
// 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

HTTP and Network (Java 11+)

These snippets use java.net.http introduced in Java 11. For Java 8, use HttpURLConnection or a library like Apache HttpClient.

40. HTTP GET Request

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
    .header("Accept", "application/json")
    .GET().build();

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode()); // 200
System.out.println("Body: " + response.body());

41. HTTP POST with JSON Body

import java.net.URI;
import java.net.http.*;

HttpClient client = HttpClient.newHttpClient();
String json = """
    { "title": "My Post", "body": "Content here", "userId": 1 }
    """;

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(json)).build();

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode()); // 201

42. Read JSON Response

Without a JSON library, extract values with regex. For production code, use Jackson or Gson.

import java.net.URI;
import java.net.http.*;
import java.util.regex.*;

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://jsonplaceholder.typicode.com/users/1")).build();
String json = client.send(request, HttpResponse.BodyHandlers.ofString()).body();

// Simple regex extraction (quick scripts only)
Matcher m = Pattern.compile("\"name\"\\s*:\\s*\"([^\"]+)\"").matcher(json);
if (m.find()) System.out.println("Name: " + m.group(1)); // Name: Leanne Graham

// For production, use Jackson:
// ObjectMapper mapper = new ObjectMapper();
// String name = mapper.readTree(json).get("name").asText();

Utility Patterns

43. Singleton Pattern

Thread-safe singleton using a static inner class (Bill Pugh pattern).

// Bill Pugh pattern -- lazy, thread-safe
public class DatabaseConnection {
    private DatabaseConnection() {}

    private static class Holder {
        private static final DatabaseConnection INSTANCE = new DatabaseConnection();
    }

    public static DatabaseConnection getInstance() { return Holder.INSTANCE; }
    public void query(String sql) { System.out.println("Executing: " + sql); }
}

DatabaseConnection.getInstance().query("SELECT * FROM users");

// Enum singleton (recommended by Effective Java)
public enum AppConfig {
    INSTANCE;
    private String appName = "MyApp";
    public String getAppName() { return appName; }
}

44. Builder Pattern

Useful when a class has many optional parameters. Avoids telescoping constructors.

public class UserProfile {
    private final String name;
    private final int age;
    private final String email;
    private final String phone;

    private UserProfile(Builder b) {
        this.name = b.name; this.age = b.age;
        this.email = b.email; this.phone = b.phone;
    }

    public static class Builder {
        private final String name;       // required
        private int age = 0;             // optional with defaults
        private String email = "";
        private String phone = "";

        public Builder(String name) { this.name = name; }
        public Builder age(int a) { this.age = a; return this; }
        public Builder email(String e) { this.email = e; return this; }
        public Builder phone(String p) { this.phone = p; return this; }
        public UserProfile build() { return new UserProfile(this); }
    }
}

// Usage -- readable, no telescoping constructors
UserProfile user = new UserProfile.Builder("Alice")
    .age(30).email("alice@example.com").build();

45. Convert Between Common Types

import java.util.*;
import java.util.stream.Collectors;

// Array <-> List
String[] array = {"a", "b", "c"};
List list = new ArrayList<>(Arrays.asList(array));
String[] back = list.toArray(new String[0]);

// int[] <-> List
int[] intArr = {1, 2, 3};
List intList = Arrays.stream(intArr).boxed().collect(Collectors.toList());
int[] backInt = intList.stream().mapToInt(Integer::intValue).toArray();

// List <-> Set
Set set = new HashSet<>(list);
List fromSet = new ArrayList<>(set);

// String <-> char[] and byte[]
char[] chars = "Hello".toCharArray();
String s = new String(chars);
byte[] bytes = "Hello".getBytes();
String s2 = new String(bytes);

46. Null-Safe Operations with Optional

import java.util.Optional;

Optional name = Optional.of("Alice");
Optional empty = Optional.empty();

// Get with default
System.out.println(name.orElse("Unknown")); // Alice
System.out.println(empty.orElse("Default")); // Default

// Get or throw
String value = name.orElseThrow(() -> new IllegalStateException("Required"));

// Transform and filter
String upper = name.map(String::toUpperCase).orElse("");
System.out.println(upper); // ALICE

name.ifPresent(n -> System.out.println("Hello, " + n)); // Hello, Alice

// Null-safe deep access (avoids NPE chains)
String zip = Optional.ofNullable(user)
    .map(User::getAddress).map(Address::getCity)
    .map(City::getZip).orElse("N/A");

47. Measure Execution Time

import java.time.Duration;
import java.time.Instant;

// System.nanoTime (most precise)
long start = System.nanoTime();
performExpensiveOperation();
System.out.printf("Elapsed: %.2f ms%n", (System.nanoTime() - start) / 1e6);

// Instant + Duration (readable, type-safe)
Instant t0 = Instant.now();
performExpensiveOperation();
Duration elapsed = Duration.between(t0, Instant.now());
System.out.println("Elapsed: " + elapsed.toMillis() + " ms");

// Reusable timing utility
public static  T timed(String label, java.util.function.Supplier task) {
    long t = System.nanoTime();
    T result = task.get();
    System.out.printf("%s took %.2f ms%n", label, (System.nanoTime() - t) / 1e6);
    return result;
}

Quick Reference Table

Task Key Class / Method Min Java
Reverse string new StringBuilder(s).reverse() 5
Sort array Arrays.sort() 2
Remove duplicates stream().distinct() 8
Filter list stream().filter() 8
Group elements Collectors.groupingBy() 8
Read file Files.readString() 11
Write file Files.writeString() 11
Current date LocalDate.now() 8
Format date DateTimeFormatter.ofPattern() 8
HTTP request HttpClient.newHttpClient() 11
Text blocks """ ... """ 15
Records record Name(fields) {} 16
Null safety Optional.ofNullable() 8
Measure time System.nanoTime() 5



Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *