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.
