Languages
[Edit]
EN

Java - uppercase all ArrayList elements

0 points
Created by:
Warren-X
443

In this article, we would like to show you how to uppercase all ArrayList elements in Java.


1. Using for loop

In this example, we use for loop to transform all the elements from letters ArrayList to uppercase.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();
        letters.add("a");
        letters.add("b");
        letters.add("c");

        for (int i = 0; i < letters.size(); i++) {
            String newValue = letters.get(i).toUpperCase(Locale.ROOT);
            letters.set(i, newValue);
        }

        System.out.println(letters);
    }
}

Output:

[A, B, C]

2. Using for-each loop

In this example, we use for-each loop to transform all the elements from letters ArrayList to uppercase.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();
        letters.add("a");
        letters.add("b");
        letters.add("c");

        for (String letter : letters) {
            String newValue = letter.toUpperCase(Locale.ROOT);
            letters.set(letters.indexOf(letter), newValue);
        }

        System.out.println(letters);
    }
}

Output:

[A, B, C]

3. Using streams

In this example, we use a stream with map() function to transform all the elements from letters ArrayList to uppercase and collect them in the new ArrayList - lettersToUpper.

import java.util.*;
import java.util.stream.Collectors;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();
        letters.add("a");
        letters.add("b");
        letters.add("c");

        System.out.println("Before: " + letters);

        List<String> lettersToUpper = letters.stream()
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        System.out.println("After:  " + lettersToUpper);
    }
}

Output:

Before: [a, b, c]
After:  [A, B, C]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join