What is map in java 8
In Java 8, the map
method is part of the Stream API, and it is used for transforming each element of a stream using a given function. It applies the provided function to each element in the stream and produces a new stream of the transformed elements. The original stream remains unchanged.
Here’s a basic example using map
to convert a stream of strings to uppercase:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "orange");
// Using map to convert each element to uppercase
List<String> uppercasedWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Print the transformed elements
System.out.println(uppercasedWords);
}
}
words.stream()
converts the List of strings (words
) into a stream..map(String::toUpperCase)
applies thetoUpperCase
method to each element of the stream, transforming each string to its uppercase version..collect(Collectors.toList())
collects the transformed elements into a new List.
The result is a new List containing the uppercase versions of the original strings.
You can use map
with any function that transforms the elements of the stream. It is a powerful and versatile operation, commonly used for tasks like extracting specific properties from objects, transforming data, or performing calculations on each element of the stream.
see another example of map in java8
int[] num = {1, 2, 3, 4, 5};
Integer[] result = Arrays.stream(num)
.map(x -> x * 2)
.boxed()
.toArray(Integer[]::new);
System.out.println(Arrays.asList(result));
output- [2, 4, 6, 8, 10]