How do I filter a list using a stream in Java?

You can use the Stream API’s filter() method to select elements that match a condition.

In this example, you will select numbers greater than or equal to 20 from a list and collect them into a new list.

Source code

Save the following code as FilterListExample.java:

import java.util.List;

public class FilterListExample {
    void main() {
        List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

        List<Integer> filteredNumbers = numbers.stream()
                .filter(number -> number >= 20)
                .toList();

        IO.println("Original list: " + numbers);
        IO.println("Filtered list: " + filteredNumbers);
    }
}

Explanation

The original list contains six integers:

List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

The following pipeline selects the matching values and collects them:

List<Integer> filteredNumbers = numbers.stream()
        .filter(number -> number >= 20)
        .toList();

Each step has a purpose:

Step Purpose
stream() Creates a sequential stream of the list’s elements
filter(...) Keeps elements that match the condition
toList() Collects the selected elements into a list

Defining the condition

The filter() method accepts a predicate: a function that checks an element and returns true or false.

Here, the predicate is a lambda expression:

number -> number >= 20

When the result is true, the number remains in the stream. When it is false, the number is excluded.

For this input, the matching values are 20, 35, and 40.

Collecting the result

filter() is an intermediate operation. It describes the selection but does not process the elements until a terminal operation runs.

In this example, toList() is the terminal operation:

.toList()

It collects the matching elements into an unmodifiable list. Calling add() or remove() on that result would throw an UnsupportedOperationException.

The result preserves the original list’s encounter order. Filtering does not change the original list.

Run the example

Compile and run the file:

javac FilterListExample.java
java FilterListExample

Output

Original list: [5, 20, 12, 35, 8, 40]
Filtered list: [20, 35, 40]

Combining conditions

Use && to require multiple conditions. For example, this filter keeps numbers that are at least 20 and even:

.filter(number -> number >= 20 && number % 2 == 0)

With the same input, the resulting list is:

[20, 40]

If no elements match the condition, toList() returns an empty list.

How do I animate a fractal tree in Java Swing?

You can draw a fractal tree by creating a branch and recursively drawing two shorter branches at its endpoint. Repeating this rule produces an intricate tree from a small amount of code.

In this SwingLoops example, the branches grow over time, sway gently, and fade away before the next cycle. Everything is drawn with Java Swing and Java 2D.

Fractal Tree Bloom

Fractal Tree Bloom

Source code

Save the following code as FractalTreeBloom.java:

package org.kodejava.swing.animation;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;

public class FractalTreeBloom extends JPanel {
    private static final int WIDTH = 450;
    private static final int HEIGHT = 800;
    private static final int LEVELS = 9;
    private static final double CYCLE = 12.0;

    private final Timer timer = new Timer(16, _ -> repaint());
    private long startedAt;

    public FractalTreeBloom() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(new Color(7, 13, 25));
    }

    @Override
    public void addNotify() {
        super.addNotify();
        startedAt = System.nanoTime();
        timer.start();
    }

    @Override
    public void removeNotify() {
        timer.stop();
        super.removeNotify();
    }

    private static double clamp(double value) {
        return Math.max(0, Math.min(1, value));
    }

    private static double smooth(double value) {
        return value * value * (3 - 2 * value);
    }

    private void branch(Graphics2D g, double x, double y,
                        double angle, double length, int level,
                        double growth, double spread, float fade) {
        if (level >= LEVELS) {
            return;
        }

        double local = smooth(clamp(growth - level));
        if (local <= 0) {
            return;
        }

        double endX = x + length * local * Math.cos(angle);
        double endY = y + length * local * Math.sin(angle);

        Color color = Color.getHSBColor(
                0.48f - level * 0.025f, 0.65f, 1f);
        float width = Math.max(1f, 5f - level * 0.5f);
        Line2D line = new Line2D.Double(x, y, endX, endY);

        g.setColor(color);
        g.setComposite(AlphaComposite.SrcOver.derive(fade * 0.10f));
        g.setStroke(new BasicStroke(width + 7f,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g.draw(line);

        g.setComposite(AlphaComposite.SrcOver.derive(fade));
        g.setStroke(new BasicStroke(width,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g.draw(line);

        if (local >= 1) {
            branch(g, endX, endY, angle - spread, length * 0.70,
                    level + 1, growth, spread, fade);
            branch(g, endX, endY, angle + spread, length * 0.70,
                    level + 1, growth, spread, fade);
        }
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Graphics2D g = (Graphics2D) graphics.create();

        try {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            double scale = Math.min(
                    getWidth() / (double) WIDTH,
                    getHeight() / (double) HEIGHT);
            g.translate((getWidth() - WIDTH * scale) / 2,
                    (getHeight() - HEIGHT * scale) / 2);
            g.scale(scale, scale);

            double seconds = (System.nanoTime() - startedAt) / 1e9;
            double t = seconds % CYCLE;
            double growth = Math.min(LEVELS, t * LEVELS / 7.5);
            double wind = Math.sin(2 * Math.PI * t / 6.0);
            double spread = Math.toRadians(25 + 3 * wind);
            float fade = (float) (1 - clamp((t - 10) / 2));

            branch(g, WIDTH / 2.0, 685,
                    -Math.PI / 2 + 0.025 * wind,
                    130, 0, growth, spread, fade);
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Fractal Tree Bloom");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new FractalTreeBloom());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

You need a JDK and a desktop environment that supports Swing. From the directory containing the file, run:

javac FractalTreeBloom.java
java FractalTreeBloom

The application opens a portrait window with a preferred drawing area of 450 × 800 pixels. Resizing preserves the drawing’s proportions. Close the window to exit.

Draw one branch

Each branch starts at (x, y) and extends in the direction given by angle. Sine and cosine convert its length and angle into an endpoint:

double endX = x + length * local * Math.cos(angle);
double endY = y + length * local * Math.sin(angle);

The local value controls how much of the branch is visible. Zero means no visible length; one means the branch has reached its full length.

The trunk starts at an angle of -Math.PI / 2. Swing’s vertical coordinates increase downward, so this angle points upward.

Repeat the rule with recursion

When a branch finishes growing, it creates two children at its endpoint:

branch(g, endX, endY, angle - spread, length * 0.70,
        level + 1, growth, spread, fade);
branch(g, endX, endY, angle + spread, length * 0.70,
        level + 1, growth, spread, fade);

The children turn in opposite directions and have 70% of their parent’s length. Each child follows the same rule.

The method stops when level reaches LEVELS. With nine levels, numbered zero through eight, a completed tree contains:

1 + 2 + 4 + ... + 256 = 511 branches

The stopping condition matters: without it, the recursive calls would continue until the program exhausted its stack.

Reveal the levels over time

The growth value increases from zero to nine over 7.5 seconds. Each branch subtracts its level to obtain its own progress:

double local = smooth(clamp(growth - level));

For example, when growth is 2.5, the trunk and level-one branches are complete. Level-two branches are halfway through their growth, and deeper levels are still hidden.

The smoothstep function eases the motion:

return value * value * (3 - 2 * value);

Its slope is zero at both ends, so a branch begins and finishes growing gently.

Add wind, color, and glow

A sine function changes the branching angle slightly over time. The same wind value also tilts the trunk. This creates a stylized sway; the code does not simulate forces or flexible wood.

The hue changes with branch level, giving the trunk and tips different colors. Each branch is drawn twice: a wide transparent stroke creates a halo, and a thinner bright stroke forms the visible branch.

Growth finishes at 7.5 seconds. The completed tree continues swaying, then fades from ten to twelve seconds. At the cycle boundary, growth returns to zero and the tree starts again.

Update the animation with Swing

A Swing timer requests repaints approximately every 16 milliseconds. Positions depend on elapsed time rather than frame counts, so delayed repaints do not change the intended cycle duration.

The interface is created on Swing’s event-dispatch thread. The timer starts when the panel becomes displayable and stops when it is removed. A copied Graphics2D context is disposed after each repaint.

Customize the tree

Try changing the branch-length multiplier from 0.70 to 0.65 in both recursive calls. The tree becomes more compact because each generation shrinks faster.

You can also adjust:

Setting Effect
LEVELS Tree detail. Each extra level approximately doubles the branch count.
130 Initial trunk length.
25 + 3 * wind Base branching angle and its variation, in degrees.
7.5 Time taken to reveal all levels.
width + 7f Width of the glow stroke.

Larger lengths, wider branching angles, or more levels may require changes to the scale or trunk position to keep the tree inside the canvas.

The complete source above is free to copy and run. Explore the SwingLoops repository for more Java animation examples.

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.