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 create, load, and display an image in Java?

In this example, you will draw a blue card in memory, save it as a PNG file, open that file, and show the loaded image in a Swing window. The program creates its own image.

What is a pixel?

A raster image is a grid of pixels. In a BufferedImage, the top-left pixel is at (0, 0). The x coordinate increases to the right, and the y coordinate increases downward.

This example uses BufferedImage.TYPE_INT_ARGB. Each pixel has four values for alpha, red, green, and blue. Alpha controls opacity. A value of 0 means fully transparent, and 255 means fully opaque. The program draws inside the image and leaves a transparent border, which PNG preserves when you save the file.

Java example

Save the following code as JavaImageBasics.java.

package org.kodejava.awt.image;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class JavaImageBasics {
    public static void main(String[] args) throws IOException {
        BufferedImage image = createImage();

        File file = new File("java-image.png");
        if (!ImageIO.write(image, "png", file)) {
            throw new IOException("PNG writer is unavailable");
        }

        BufferedImage loadedImage = ImageIO.read(file);
        if (loadedImage == null) {
            throw new IOException("Unrecognized image format: " + file);
        }

        System.out.printf("%s: %d x %d pixels%n",
                file.getName(), loadedImage.getWidth(), loadedImage.getHeight());

        if (!GraphicsEnvironment.isHeadless()) {
            SwingUtilities.invokeLater(() -> showImage(loadedImage));
        }
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(
                320, 200, BufferedImage.TYPE_INT_ARGB);

        Graphics2D graphics = image.createGraphics();
        try {
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setColor(new Color(33, 99, 200));
            graphics.fillRoundRect(20, 20, 280, 160, 30, 30);
            graphics.setColor(Color.WHITE);
            graphics.drawString("Hello, Java Images!", 100, 105);
        } finally {
            graphics.dispose();
        }

        return image;
    }

    private static void showImage(BufferedImage image) {
        JFrame frame = new JFrame("Java Images");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel(new ImageIcon(image)));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Run the program

Open a terminal in the folder containing the Java file and run these commands.

javac JavaImageBasics.java
java JavaImageBasics

The program writes java-image.png to the working directory and prints the dimensions of the loaded file.

Java Image

java-image.png: 320 x 200 pixels

On a desktop, a Swing window shows the blue card. The transparent border lets the component background show through. In a headless environment, the program still writes and reads the file and prints its dimensions.

How it works

  1. Create. createGraphics() returns a Graphics2D object that draws directly into the BufferedImage. The finally block calls dispose() to release the drawing context.
  2. Save. ImageIO.write() selects an encoder using the format name "png". It returns false if no suitable writer is available.
  3. Load. ImageIO.read() decodes the file into a new BufferedImage. It returns null if no installed reader recognizes the data. An error while opening or reading the file can throw an IOException.
  4. Display. ImageIcon wraps the loaded image, and JLabel displays the icon. SwingUtilities.invokeLater() creates the window on Swing’s Event Dispatch Thread after the file has been read.

Try it yourself

Change the image size to 480 × 240 pixels. Resize the blue rectangle so it still has a 20-pixel margin on all sides. Then print the alpha value for the top-left pixel and for a pixel inside the blue rectangle.

int cornerAlpha = loadedImage.getRGB(0, 0) >>> 24;
int cardAlpha = loadedImage.getRGB(30, 50) >>> 24;
System.out.printf("Corner alpha = %d, card alpha = %d%n",
        cornerAlpha, cardAlpha);

Add this snippet after the null check in main(). The expected values are 0 for the transparent corner and 255 for the solid blue area.

Maven dependencies

AWT, Swing, and Image I/O are part of the JDK’s java.desktop module. This example needs no extra Maven dependencies. If you use a modular project, add requires java.desktop; to your module declaration.

References

Next week — How do I choose an image file format in Java?

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 keep a recent files list with SequencedMap in Java 21?

A recent files menu should move a reopened file to the top instead of showing it twice. Once the menu is full, opening a new file should remove the oldest entry. In Java 21, a LinkedHashMap can do both through the SequencedMap interface. See the Java 21 SequencedMap API.

1. Move a reopened file to the newest position

Use a LinkedHashMap to store each file name and its path. The example keeps the oldest entry first and the newest entry last.

On a default LinkedHashMap, calling put() for an existing key changes its value but leaves it in the same position. Calling putLast() also moves the entry to the end. That means reopening notes.txt makes it the newest entry without adding a duplicate. See the Java 21 LinkedHashMap API.

2. Remove the oldest entry when the list is full

After recording a file, check the map’s size. If it exceeds the limit, call pollFirstEntry() to remove and return the oldest entry. Use reversed() when displaying the menu so the newest entry appears first.

3. Run the complete example

Save this code as RecentFilesExample.java. The paths are sample strings; the program does not open any files.

import java.util.LinkedHashMap;
import java.util.SequencedMap;

public class RecentFilesExample {
    private static final int LIMIT = 3;

    public static void main(String[] args) {
        SequencedMap<String, String> recent = new LinkedHashMap<>();

        remember(recent, "notes.txt", "/work/notes.txt");
        remember(recent, "plan.txt", "/work/plan.txt");
        remember(recent, "ideas.txt", "/work/ideas.txt");
        remember(recent, "notes.txt", "/work/notes.txt");

        System.out.println("After reopening: " + recent.sequencedKeySet());

        var removed = remember(recent, "draft.txt", "/work/draft.txt");
        System.out.println("Removed: " + removed);
        System.out.println("Newest first: " + recent.reversed().sequencedKeySet());
    }

    private static String remember(SequencedMap<String, String> recent,
                                   String name, String path) {
        recent.putLast(name, path);
        if (recent.size() > LIMIT) {
            return recent.pollFirstEntry().getKey();
        }
        return null;
    }
}

Compile and run it from the directory containing the file:

javac --release 21 RecentFilesExample.java
java RecentFilesExample

Output:

After reopening: [plan.txt, ideas.txt, notes.txt]
Removed: plan.txt
Newest first: [draft.txt, notes.txt, ideas.txt]

Reopening notes.txt makes plan.txt the oldest entry. Adding draft.txt takes the map over its three-file limit, so plan.txt is removed.

Best practices

  • Use a full path or another stable identifier as the key in a real app. Two folders can contain files with the same name.
  • Update the list after a file opens successfully so failed attempts do not appear in the menu.
  • Treat reversed() as a live view. If you need a list that stays the same when the map changes, take a snapshot with List.copyOf(recent.reversed().sequencedKeySet()).

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.