Apply a function to each item of a List in Java
This post will discuss how to apply a function to each item of a List in Java.
1. Using List.replaceAll() method
The List interface provides the replaceAll() method, which can be used to apply a specified operator to each element of the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("a", "b", "c", "d"); words.replaceAll(String::toUpperCase); System.out.println(words); } } |
Output:
[A, B, C, D]
2. Using Stream.map() method
With Java 8 Stream API, you can get a sequential stream over the list and call the map() method to apply a given function to the elements of the stream. This approach can be used when you need a new list, and leave the original list unchanged.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("a", "b", "c", "d"); List<String> caps = words.stream().map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(caps); } } |
Output:
[A, B, C, D]
This is equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("a", "b", "c", "d"); List<String> caps = new ArrayList<>(); for (String word : words) { caps.add(word.toUpperCase()); } System.out.println(caps); } } |
Output:
[A, B, C, D]
3. Using Guava
If you use the Guava library in your project, you may want to use the Lists.transform() method. It returns a new list after applying a specified function to each element of the original list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("a", "b", "c", "d"); List<String> caps = Lists.transform(words, word -> word.toUpperCase()); System.out.println(caps); } } |
Output:
[A, B, C, D]
That’s all about applying a function to each item of a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)