Languages
[Edit]
EN

Java - lowercase all ArrayList elements

0 points
Created by:
rmlocerd
302

In this article, we would like to show you how to lowercase 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 lowercase.

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).toLowerCase(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 lowercase.

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.toLowerCase(Locale.ROOT);
            letters.set(letters.indexOf(letter), newValue);
        }

        System.out.println(letters);
    }
}

Output:

[a, b, c]

3. Using streams

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

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> lettersToLower = letters.stream()
                .map(String::toLowerCase)
                .collect(Collectors.toList());

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

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