iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Examples

Six worked Java examples: HTTP client, records, streams, async with CompletableFuture, file IO, JUnit test.

Java — examples

EXAMPLE
// ===== 1. HTTP client (java.net.http) =====
import java.net.http.*;
import java.net.URI;

var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder(URI.create("https://api.github.com/repos/openjdk/jdk"))
    .header("Accept", "application/json")
    .build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.statusCode() + " " + resp.body().length());

// ===== 2. Records + pattern matching =====
public record User(int id, String name, String email) {}

User u = new User(1, "Alex", "a@x.io");
String size = switch (u.id()) {
    case 0 -> "none";
    case Integer n when n < 100 -> "small";
    default -> "big";
};

// ===== 3. Streams =====
import java.util.*;
import java.util.stream.*;

var nums = List.of(1, 2, 3, 4, 5);
var evens = nums.stream().filter(n -> n % 2 == 0).map(n -> n * n).toList();
System.out.println(evens);   // [4, 16]

int sum = nums.stream().mapToInt(Integer::intValue).sum();

Map<String, Long> byTag = users.stream().collect(Collectors.groupingBy(User::name, Collectors.counting()));

// ===== 4. CompletableFuture (async) =====
import java.util.concurrent.*;

CompletableFuture<String> fa = CompletableFuture.supplyAsync(() -> fetchA());
CompletableFuture<String> fb = CompletableFuture.supplyAsync(() -> fetchB());

CompletableFuture<String> combined = fa.thenCombine(fb, (a, b) -> a + " / " + b);
System.out.println(combined.get(5, TimeUnit.SECONDS));

CompletableFuture.allOf(fa, fb).join();

// ===== 5. File I/O (java.nio.file) =====
import java.nio.file.*;
import java.util.List;

Path p = Path.of("data.txt");
String text = Files.readString(p);
List<String> lines = Files.readAllLines(p);
Files.writeString(Path.of("out.txt"), "hello");

// Stream a big file:
try (var stream = Files.lines(p)) {
    stream.filter(l -> l.contains("ERROR")).forEach(System.out::println);
}

// ===== 6. JUnit 5 test =====
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class MathTest {
    @Test
    void onePlusOne() {
        assertEquals(2, 1 + 1);
    }

    @Test
    void throwsOnDivByZero() {
        assertThrows(ArithmeticException.class, () -> { int x = 1 / 0; });
    }
}

// ===== 7. Virtual threads (Project Loom, Java 21+) =====
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 1000; i++) {
        executor.submit(() -> {
            Thread.sleep(1000);
            return null;
        });
    }
}
// Throughput vs platform threads: orders of magnitude better.

// ===== Patterns =====
// - Records for DTOs
// - Streams for collection transforms
// - CompletableFuture / virtual threads for async
// - java.nio.file.Files for IO
// - JUnit 5 + AssertJ for tests

// ===== Pitfalls =====
// - Long stream chains in hot loops -> regular loops can be faster
// - Forgetting to close streams (try-with-resources)
// - Catching Exception broadly
// - Blocking calls on platform threads when virtual threads exist

Why it matters

Six worked Java examples: HTTP, records + pattern matching, streams, CompletableFuture, NIO file IO, JUnit. Modern Java 21 reads cleaner than its reputation; pin these as the start of any sprint.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// See the lesson body for ready-to-paste snippets.
Try it Yourself »

Discussion

Loading…