EN
Java - lowercase all ArrayList elements
0
points
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]