JvJava

Java: More snippets – code examples

Contents

Method with overloading

Functions#method#return#overloadCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
public class Main {
    static String begruesse(String name, String gruss) {
        return gruss + ", " + name + "!";
    }
    static String begruesse(String name) {
        return begruesse(name, "Hello");
    }
    public static void main(String[] args) {
        System.out.println(begruesse("Ada"));
        System.out.println(begruesse("Linus", "Hi"));
    }
}

Java has no default values for parameters. The analogue is overloading: the one-parameter variant calls the other one with a default value.

Read and write a file

Files#files#path#file#nioCompare in all languages
Use case: Save and load logs, configurations or text data.
import java.io.IOException;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Path datei = Path.of("notizen.txt");
        Files.writeString(datei, "Line 1\nLine 2\n");
        for (String zeile : Files.readAllLines(datei)) {
            System.out.println(zeile.strip());
        }
    }
}

Files from java.nio.file takes care of opening and closing itself. The IOException is checked and is passed on here with throws.

Streams: grouping and evaluating

Streams#stream#groupingby#collectors
Use case: Group data from databases or CSV files, e.g. users per city.
import java.util.*;
import java.util.stream.*;

public class Main {
    record Person(String name, String stadt, int alter) {}
    public static void main(String[] args) {
        var leute = List.of(new Person("Ada", "London", 36),
                new Person("Bob", "Berlin", 25), new Person("Eva", "Berlin", 31));
        var proStadt = leute.stream().collect(Collectors.groupingBy(Person::stadt,
                TreeMap::new, Collectors.mapping(Person::name, Collectors.toList())));
        System.out.println(proStadt);
        double schnitt = leute.stream().mapToInt(Person::alter).average().orElse(0);
        System.out.println(Math.round(schnitt));
    }
}

groupingBy corresponds to GROUP BY; TreeMap::new sorts the keys. Output: {Berlin=[Bob, Eva], London=[Ada]} and 31 (average 30.67, rounded).

Combining CompletableFuture

Concurrency#completablefuture#async#parallel
Use case: Start several independent queries (price, discount) in parallel and merge them.
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        var preis = CompletableFuture.supplyAsync(() -> 100.0);
        var rabatt = CompletableFuture.supplyAsync(() -> 0.2);
        var endpreis = preis.thenCombine(rabatt, (p, r) -> p * (1 - r));
        System.out.println(endpreis.join());
    }
}

Both tasks run in parallel; thenCombine joins the results, join waits for the result. Output: 80.0.

Virtual threads

Concurrency#virtual#thread#loom#executor
Use case: Thousands of blocking tasks (HTTP calls, DB queries) without complicated async code.
import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<Integer>> futures = new ArrayList<>();
            for (int i = 1; i <= 5; i++) {
                int n = i;
                futures.add(executor.submit(() -> { Thread.sleep(100); return n * n; }));
            }
            for (var f : futures) System.out.println(f.get());
        }
    }
}

Java 21: one virtual thread per task. Output: 1, 4, 9, 16, 25 – the five wait times overlap.

Generic method

Generics#generics#comparable
Use case: Write helper functions that work with any comparable type.
import java.util.List;

public class Main {
    static <T extends Comparable<T>> T maximum(List<T> liste) {
        T max = liste.get(0);
        for (T x : liste) {
            if (x.compareTo(max) > 0) max = x;
        }
        return max;
    }
    public static void main(String[] args) {
        System.out.println(maximum(List.of(3, 9, 4)));
        System.out.println(maximum(List.of("pear", "apple")));
    }
}

T extends Comparable<T> allows only types that can be compared. Output: 9 and pear.

HTTP request (HttpClient)

Networking#http#api#httpclient
Use case: Fetch data from a web API – without any external library.
import java.net.URI;
import java.net.http.*;

public class Main {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.github.com/repos/openjdk/jdk"))
                .header("Accept", "application/json").build();
        HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
        System.out.println(res.statusCode());
        System.out.println(res.body().length() + " characters");
    }
}

The HttpClient has been part of the standard library since Java 11. For JSON parsing you additionally need e.g. Jackson or Gson.