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 Use Kotlin to Model Tasks in an Android App?

In article 1, you created Task Notes and its empty screen. Now you will describe the data behind a task using Kotlin. You will create a Task model, prepare sample tasks, and display one task on the existing screen. The next article will turn those samples into a scrolling list.

Practical goal

By the end, you will be able to declare typed properties, use default and named arguments, create a read-only list, and produce an updated task with copy().

Continue with the same Android Studio project. This example keeps the package org.kodejava.tasknotes, the generated TaskNotesTheme, and minimum SDK API 24 from article 1. If you used your own package, adjust the package declarations and imports below.

1. Create the Task model

Create the model package below org.kodejava.tasknotes. Add this file:

File: app/src/main/java/org/kodejava/tasknotes/model/Task.kt

package org.kodejava.tasknotes.model

data class Task(
    val id: Long,
    val title: String,
    val isCompleted: Boolean = false
)

A model describes information that the app works with. Here, each task has three properties:

Property Type Purpose
id Long Identifies the task even when its title changes
title String Holds the text shown to the user
isCompleted Boolean Records whether the task is done

The colon introduces a type. Boolean has two values: true and false. The default value means a new task starts incomplete unless you supply another value.

String does not accept null. It still accepts empty text such as ""; non-null types do not replace input validation. You will add form validation in a later article.

The data keyword asks Kotlin to generate useful operations such as equality checks, readable text output, and copying. Keep the properties in the primary constructor so those generated operations include them. See the official data class documentation.

2. Understand val and named arguments

This is an example of constructing a task; you do not need to add it to a file yet:

val task = Task(id = 1L, title = "Learn Kotlin basics")

val declares a reference that cannot be reassigned. The model also uses val properties, so you cannot assign a new title directly to an existing task.

1L is a Long literal. Named arguments such as title = ... make constructor calls easier to read. Since we omitted isCompleted, its value is false.

Kotlin also has var for variables that can be reassigned. We use val here to make changes explicit through new objects.

3. Prepare reusable sample data

Create a data package and add the following file:

File: app/src/main/java/org/kodejava/tasknotes/data/SampleTasks.kt

package org.kodejava.tasknotes.data

import org.kodejava.tasknotes.model.Task

fun sampleTasks(): List<Task> = listOf(
    Task(id = 1L, title = "Learn Kotlin basics"),
    Task(id = 2L, title = "Create the Task model", isCompleted = true),
    Task(id = 3L, title = "Build the task list")
)

fun declares a function. This function takes no arguments and returns a List<Task>, meaning a list whose elements are tasks. The = introduces a function with a single expression as its body.

listOf() creates the sample list. List exposes read-only operations: callers can inspect its elements but cannot call add() through that interface. A read-only interface is not a general guarantee that an underlying collection can never change. Our sample contains tasks with read-only properties and exposes no mutation operations.

The sample IDs are distinct and remain the same each time this function is called. They are manually assigned tutorial values; the function does not generate IDs for future user-created tasks. A title is not an ID because two tasks may have the same title.

Reference: Kotlin collections overview.

4. Display a task on the existing screen

In MainActivity.kt, add this import alongside the existing imports:

import org.kodejava.tasknotes.data.sampleTasks

Replace only the existing TaskNotesScreen() function with the code below. Keep MainActivity, its Scaffold and innerPadding, all existing Compose imports, and TaskNotesScreenPreview() from article 1.

File: app/src/main/java/org/kodejava/tasknotes/MainActivity.kt

@Composable
private fun TaskNotesScreen(modifier: Modifier = Modifier) {
    val tasks = sampleTasks()
    val task = tasks.first()
    val status = if (task.isCompleted) "Completed" else "Not completed"

    Column(
        modifier = modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            text = task.title,
            style = MaterialTheme.typography.bodyLarge
        )
        Text(text = "Status: $status")
        Text(text = "Sample tasks: ${tasks.size}")
    }
}

Kotlin infers the types of tasks, task, and status from their values. first() reads the first element. It is safe here because our sample function always returns three tasks; it would throw an exception for an empty list.

An if expression produces the status text. String templates insert values into text: $status inserts a variable, while ${tasks.size} evaluates an expression.

This screen only reads fixed sample data. Calling sampleTasks() during composition is acceptable for this tiny example; it is not a strategy for loading database data. Interactive state and its ownership come later in the series.

5. Create an updated task with copy()

To try a completed version, replace this line inside TaskNotesScreen():

val task = tasks.first()

with:

val original = tasks.first()
val task = original.copy(isCompleted = true)

The copied task keeps the original ID and title but has a new completion value. The original task and the task stored in the sample list remain incomplete. Copying an object does not replace an element in a list.

copy() is shallow: nested objects would still be shared. This model contains only a number, text, and a Boolean, so no mutable nested collection is involved.

After checking the result, restore val task = tasks.first() so your project matches the starting point for article 3.

6. Verify the result

  1. Sync the project if Android Studio requests it, then run the app on the emulator or phone used in article 1.
  2. Check that the screen shows the following text:
Task Notes
Learn Kotlin basics
Status: Not completed
Sample tasks: 3
  1. Refresh the existing Compose preview. It should show the same sample content.
  2. Try the copy() change from step 5. The status should become Completed, with the same title and sample count.
  3. Restore the original line and run again.

If Task or sampleTasks is unresolved, check the file package declarations and imports. If the compiler reports a type mismatch for an ID, use a Long literal such as 1L. If the preview cannot load, resolve build errors before refreshing it.

These are verification steps for your project. This draft’s Android build and device behavior have not been executed in an Android SDK environment.

Practice

  • Add a fourth sample task with ID 4L. Verify that the count becomes 4.
  • Display tasks[1] instead of the first task. The second task should show Completed. List indexes start at zero.
  • Use copy(title = "Review Kotlin basics") on the first task and observe that the original sample title stays unchanged.

Restore the three original samples and tasks.first() before continuing to the next article.

Gradle dependencies and compatibility

No additional Gradle dependencies are required. The model and sample function use the Kotlin standard library supplied by the existing Kotlin Android project. The screen reuses the Compose dependencies configured in article 1.

Keep the existing plugin and dependency versions in build.gradle.kts, app/build.gradle.kts, and gradle/libs.versions.toml if present. This lesson introduces no version-specific library API and does not require a Kotlin, Android Gradle Plugin, or Compose upgrade. Official Compose setup guidance remains the reference for project configuration.

Next in the series

In article 3, How Do I Display Tasks in a LazyColumn with Jetpack Compose?, you will reuse Task and sampleTasks() to render the task list.

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.