In Java 8 and later, you can use the Stream
API to iterate over the elements of a List
and perform operations on them.
To iterate over the elements of a List
and perform operations on them, you can use the map
method of the Stream
interface to apply a function to each element of the List
, and the forEach
method to perform an action on each element of the List
.
Here is an example of how you can use the map
and forEach
methods to iterate over the elements of a List
and manipulate them:
import java.util.List; import java.util.Arrays; public class MyClass { public static void main(String[] args) { List<String> words = Arrays.asList("apple", "banana", "cherry"); // Convert the words to uppercase words.stream() .map(String::toUpperCase) .forEach(System.out::println); // Outputs "APPLE", "BANANA", "CHERRY" // Add a prefix to each word words.stream() .map(s -> "PREFIX: " + s) .forEach(System.out::println); // Outputs "PREFIX: apple", "PREFIX: banana", "PREFIX: cherry" } }
In this example, the words
List
contains three strings: "apple", "banana", and "cherry".
The first map
operation applies the toUpperCase
method to each element of the List
, and the forEach
operation prints the uppercase versions of the words to the console.