1. Introduction
This tutorial covers the map() method in the Java Stream API. The map() is an intermediate operation that transforms each element in a stream using a provided function. This method is key for data transformation tasks, allowing each element in the stream to be mapped to a new form.
Key Points
1. map() applies a function to each element of a stream, transforming them into a new form based on the function's logic.
2. It returns a new stream consisting of the results of applying the function to the elements of the original stream.
3. This method is commonly used for converting data types, changing the structure of elements, or extracting information from complex objects.
2. Program Steps
1. Create a Stream of elements.
2. Apply the map() method to transform these elements.
3. Collect or process the results to demonstrate the transformations.
3. Code Program
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamMapExample {
public static void main(String[] args) {
// Stream of numbers
Stream<Integer> numberStream = Stream.of(1, 2, 3, 4, 5);
// Transform numbers into their squares
List<Integer> squares = numberStream.map(n -> n * n).collect(Collectors.toList());
System.out.println("Squares: " + squares);
// Stream of words
Stream<String> wordsStream = Stream.of("hello", "world", "java", "stream");
// Transform words into uppercase
List<String> uppercaseWords = wordsStream.map(String::toUpperCase).collect(Collectors.toList());
System.out.println("Uppercase Words: " + uppercaseWords);
}
}
Output:
Squares: [1, 4, 9, 16, 25] Uppercase Words: [HELLO, WORLD, JAVA, STREAM]
Explanation:
1. Stream.of(1, 2, 3, 4, 5) creates a stream of integers.
2. numberStream.map(n -> n * n) applies a function to each integer to compute its square and returns a new stream of these squares.
3. squares.collect(Collectors.toList()) collects the results into a list and prints the squares of the original numbers.
4. Stream.of("hello", "world", "java", "stream") creates a stream of strings.
5. wordsStream.map(String::toUpperCase) applies the String.toUpperCase method reference to transform each word into uppercase.
6. uppercaseWords.collect(Collectors.toList()) collects the transformed words into a list and prints them.
Comments
Post a Comment
Leave Comment