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.

Download  Run Code

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.

Download  Run Code

Output:

[A, B, C, D]

 
This is equivalent to:

Download  Run Code

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.

Download Code

Output:

[A, B, C, D]

That’s all about applying a function to each item of a List in Java.