realNameHidden
Posted on November 10, 2024
forEach: A terminal operation that performs an action on each element of the stream but does not transform or return data.
map: An intermediate operation that transforms each element in the stream and returns a new stream of transformed elements.
Basic forEach with List
import java.util.Arrays;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Print each name using forEach
names.forEach(name -> System.out.println(name));
}
}
map example
List<String> names = Arrays.asList("Alice", "Bob");
names.stream().forEach(System.out::println); // Simply prints each name
List<Integer> nameLengths = names.stream()
.map(String::length) // Transforms each name to its length
.collect(Collectors.toList());
💖 💪 🙅 🚩
realNameHidden
Posted on November 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.