How do I model parsing success and failure with a sealed interface in Java 21?

When a user enters a number, your program needs to handle both valid and invalid input. Returning null on failure loses the reason for the error. Instead, you can return an object that represents either a parsed value or a helpful message.

This tutorial builds a small result model using a sealed interface, two records, and a pattern-matching switch.

1. Define the possible outcomes

Our parser returns a ParseResult. Its sealed declaration lists exactly two permitted implementations:

  • Success, containing an integer.
  • Failure, containing an error message.

This makes the possible outcomes visible in the type definitions.

2. Parse input at the application boundary

Before parsing, check for null or blank input. For other strings, remove surrounding whitespace and call Integer.parseInt().

Catch NumberFormatException inside the parser and convert it into a Failure. The caller can then handle both outcomes through the same return type.

3. Handle each outcome with a switch

A record pattern such as Success(int value) extracts the component into a local variable. Java 21 supports record patterns in switches. See Java’s record pattern documentation.

Because the switch covers both permitted implementations, it needs no default. If you later add another result type, recompiling this switch helps reveal the missing case. See pattern matching for switch.

4. Run the complete example

Save this code as ParseResultExample.java:

public class ParseResultExample {
    sealed interface ParseResult permits Success, Failure { }

    record Success(int value) implements ParseResult { }

    record Failure(String message) implements ParseResult { }

    static ParseResult parse(String input) {
        if (input == null || input.isBlank()) {
            return new Failure("Enter a whole number");
        }

        try {
            return new Success(Integer.parseInt(input.strip()));
        } catch (NumberFormatException exception) {
            return new Failure("Invalid or out-of-range integer");
        }
    }

    static String describe(ParseResult result) {
        return switch (result) {
            case Success(int value) -> "Parsed: " + value;
            case Failure(String message) -> "Error: " + message;
        };
    }

    public static void main(String[] args) {
        String[] inputs = {
                " 42 ", "hello", "2147483648", null
        };

        for (String input : inputs) {
            System.out.println(describe(parse(input)));
        }
    }
}

Compile and run:

javac --release 21 ParseResultExample.java
java ParseResultExample

Output:

Parsed: 42
Error: Invalid or out-of-range integer
Error: Invalid or out-of-range integer
Error: Enter a whole number

The third input contains valid digits but exceeds the maximum int value, 2147483647. It therefore follows the same failure path as invalid text. The accepted range and exception behavior are documented in Integer.parseInt().

Best practices

  • Return a result object for every expected outcome; keep null out of the result contract.
  • Catch the specific parsing exception rather than a broad Exception.
  • Use separate failure types when callers need different recovery actions.
  • Keep presentation separate from parsing, as the describe() method does here.
  • Remember that default does not handle a null switch selector. This parser always returns a non-null result.

Summary

A sealed result model makes success and failure explicit. Records carry the associated data, while an exhaustive switch gives callers a clear place to handle every outcome.

How do I convert a list of strings to uppercase using a stream in Java?

You can use the Stream API’s map() method to transform each string in a list. Call toUpperCase() inside the mapping function, then collect the results with toList().

In this example, you will convert programming language names to uppercase without changing the original list.

Source code

Save the following code as UppercaseListExample.java:

import java.util.List;
import java.util.Locale;

public class UppercaseListExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "Kotlin");

        List<String> uppercaseLanguages = languages.stream()
                .map(language -> language.toUpperCase(Locale.ROOT))
                .toList();

        IO.println("Original list: " + languages);
        IO.println("Uppercase list: " + uppercaseLanguages);
    }
}

Explanation

The original list contains three strings with mixed capitalization:

List<String> languages = List.of(
        "Java", "Python", "Kotlin");

The following pipeline transforms each element and collects the results:

List<String> uppercaseLanguages = languages.stream()
        .map(language -> language.toUpperCase(Locale.ROOT))
        .toList();

Each step has a purpose:

Step Purpose
stream() Creates a sequential stream of the list’s elements
map(...) Converts each string to uppercase
toList() Collects the converted strings into an unmodifiable list

Transforming each element

The map() method applies a function to each element:

language -> language.toUpperCase(Locale.ROOT)

For example, "Java" becomes "JAVA".

Unlike filter(), which selects matching elements, map() transforms them. This pipeline produces one result for each input element.

Choosing a locale

Uppercase conversion can depend on language rules. Calling toUpperCase() without an argument uses the system’s default locale.

This example passes Locale.ROOT explicitly:

language.toUpperCase(Locale.ROOT)

It uses language-neutral casing rules, making the conversion independent of the system’s default locale. For text intended for a specific language, use the appropriate locale instead.

Keeping the original values

Strings are immutable. Calling toUpperCase() returns an uppercase result without modifying the original string.

The stream pipeline also leaves the original list unchanged. The result list preserves the original element order.

The list returned by toList() is unmodifiable. Calling add(), remove(), or set() on it would throw an UnsupportedOperationException.

Run the example

Compile and run the file:

javac UppercaseListExample.java
java UppercaseListExample

Output

Original list: [Java, Python, Kotlin]
Uppercase list: [JAVA, PYTHON, KOTLIN]

Use map() when you want to transform every element, such as converting text, extracting an object’s field, or calculating a new value.

How do I sort a list of objects by a field in Java?

You can use Comparator.comparing() to sort objects by a field exposed through an accessor method.

In this example, you will sort a list of books alphabetically by title.

Source code

Save the following code as SortObjectsExample.java:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortObjectsExample {
    void main() {
        List<Book> books = new ArrayList<>(List.of(
                new Book("Learning Java", "Alice"),
                new Book("Exploring Java", "Bob"),
                new Book("Building Java Apps", "Carol")
        ));

        books.sort(Comparator.comparing(Book::title));

        for (Book book : books) {
            IO.println(book.title() + " by " + book.author());
        }
    }
}

record Book(String title, String author) {
}

Explanation

The Book record stores a title and an author:

record Book(String title, String author) {
}

Java provides the accessor methods title() and author() automatically.

The example creates an ArrayList containing three books. This list supports sorting, unlike the unmodifiable list returned directly by List.of().

Creating a comparator

The following expression creates a comparator that compares books by title:

Comparator.comparing(Book::title)

The method reference Book::title tells the comparator which value to extract from each book.

Because the extracted values are strings, the comparator uses their natural ordering. For these titles, that produces alphabetical order. String natural ordering is case-sensitive.

Sorting the list

Pass the comparator to sort():

books.sort(Comparator.comparing(Book::title));

This rearranges the elements in the existing list. It does not create a separate sorted list.

The loop then prints the books in their new order:

for (Book book : books) {
    IO.println(book.title() + " by " + book.author());
}

Run the example

Compile and run the file:

javac SortObjectsExample.java
java SortObjectsExample

Output

Building Java Apps by Carol
Exploring Java by Bob
Learning Java by Alice

Reversing the order

To sort titles in descending order, reverse the comparator:

books.sort(Comparator.comparing(Book::title).reversed());

Comparing another field when titles match

Use thenComparing() to compare authors when two books have equal titles:

books.sort(
        Comparator.comparing(Book::title)
                .thenComparing(Book::author)
);

This sorts by title first, then by author for books with matching titles.

How do I get the first and last elements of a List in Java?

You can use getFirst() and getLast() to read the first and last elements of a list without calculating their indexes.

In this example, you will read the first and last programming language names from a list.

Source code

Save the following code as FirstLastListExample.java:

import java.util.List;

public class FirstLastListExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "Kotlin");

        if (languages.isEmpty()) {
            IO.println("The list is empty.");
            return;
        }

        String firstLanguage = languages.getFirst();
        String lastLanguage = languages.getLast();

        IO.println("Languages: " + languages);
        IO.println("First language: " + firstLanguage);
        IO.println("Last language: " + lastLanguage);
    }
}

Explanation

The example creates a list containing three strings:

List<String> languages = List.of(
        "Java", "Python", "Kotlin");

A List maintains its elements in a defined order. Here, "Java" is the first element and "Kotlin" is the last.

Checking for an empty list

Before reading either element, the program checks whether the list is empty:

if (languages.isEmpty()) {
    IO.println("The list is empty.");
    return;
}

Both getFirst() and getLast() throw a NoSuchElementException when called on an empty list.

The return statement ends the method before either call can happen.

Reading the first element

Use getFirst() to retrieve the element at the beginning:

String firstLanguage = languages.getFirst();

For a nonempty list, this returns the same element as get(0).

Reading the last element

Use getLast() to retrieve the element at the end:

String lastLanguage = languages.getLast();

For a nonempty list, this returns the same element as:

languages.get(languages.size() - 1)

The named methods make the intent clear without requiring index calculations. Neither method removes an element or changes the list.

Run the example

Compile and run the file:

javac FirstLastListExample.java
java FirstLastListExample

Output

Languages: [Java, Python, Kotlin]
First language: Java
Last language: Kotlin

If you replace the list declaration with an empty list:

List<String> languages = List.of();

The output becomes:

The list is empty.

For a list containing only one element, getFirst() and getLast() return that same element.

How do I loop through the entries of a HashMap in Java?

You can use entrySet() with an enhanced for loop to read each key-value pair in a HashMap.

In this example, you will store product names and their quantities, then print each entry.

Source code

Save the following code as HashMapLoopExample.java:

import java.util.HashMap;
import java.util.Map;

public class HashMapLoopExample {
    void main() {
        Map<String, Integer> inventory = new HashMap<>();

        inventory.put("Notebook", 12);
        inventory.put("Pen", 30);
        inventory.put("Pencil", 20);

        for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
            String product = entry.getKey();
            int quantity = entry.getValue();

            IO.println(product + ": " + quantity);
        }

        IO.println("Total products: " + inventory.size());
    }
}

Explanation

A map stores values associated with unique keys. In this example, each product name is a key, and its quantity is the corresponding value:

Map<String, Integer> inventory = new HashMap<>();

The type arguments specify that keys are strings and values are integers. Java generics use reference types, so the value type is Integer rather than int.

Adding entries

Use put() to add a key-value pair:

inventory.put("Notebook", 12);

Java automatically boxes the quantity into an Integer.

If you call put() again with an existing key, the new value replaces the previous value for that key.

Reading entries with entrySet()

The entrySet() method provides a set view of the map’s entries:

inventory.entrySet()

Each entry contains both a key and its associated value. The enhanced for loop reads one entry at a time:

for (Map.Entry<String, Integer> entry : inventory.entrySet()) {

Inside the loop, use getKey() and getValue() to access the pair:

String product = entry.getKey();
int quantity = entry.getValue();

Assigning the Integer value to an int automatically unboxes it. All values in this example are non-null.

Using entrySet() lets you read the key and value together without performing a separate lookup with get().

Counting entries

The size() method returns the number of key-value pairs:

inventory.size()

Here, the result is 3. It counts product entries, not the sum of their quantities.

Run the example

Compile and run the file:

javac HashMapLoopExample.java
java HashMapLoopExample

Example output

Notebook: 12
Pen: 30
Pencil: 20
Total products: 3

A HashMap does not guarantee iteration order, so the product lines may appear in a different order.

Using forEach()

For a shorter alternative, replace the loop with:

inventory.forEach((product, quantity) ->
        IO.println(product + ": " + quantity));

This passes each key and value to the lambda expression. It also follows the map’s iteration order, which remains unspecified for a HashMap.