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:
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.
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:
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.
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.
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.
@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
Sync the project if Android Studio requests it, then run the app on the emulator or phone used in article 1.
Refresh the existing Compose preview. It should show the same sample content.
Try the copy() change from step 5. The status should become Completed, with the same title and sample count.
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.
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.
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.
Fractal Tree Bloom
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.
You need a JDK 25 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:
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.
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());
}