Posted in

What is map() in Java 8 Stream

In Java 8, map() is a method of the Stream interface used for transforming each element in a stream. It applies a given function to every element and returns a new stream with the transformed values.

Example 1: Convert a List of Integers to Their Squares

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Using map() to square each number
        List<Integer> squaredNumbers = numbers.stream()
                                              .map(n -> n * n)
                                              .collect(Collectors.toList());

Example 2: Convert a List of Strings to Uppercase

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StringMapExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("java", "stream", "lambda");

        // Convert all names to uppercase
        List<String> upperCaseNames = names.stream()
                                           .map(String::toUpperCase)
                                           .collect(Collectors.toList()); // Using method reference

        System.out.println(upperCaseNames); // Output: [JAVA, STREAM, LAMBDA]
    }
}

Example 2.1:

package com.learnwithrup;

import java.util.Arrays;
import java.util.List;

/**
 * Demonstrates usage of Java Stream API to convert a list of strings to
 * uppercase.
 */
public class Test {

	/**
	 * Main method to execute the example.
	 *
	 * @param args command line arguments
	 */
	public static void main(String[] args) {
		List<String> names = Arrays.asList("java", "python", "go");
		List<String> upperCaseNames1 = names.stream()
				.map(lang -> lang.toUpperCase()).toList(); // Using java 17 toList() method.

		List<String> upperCaseNames2 = names.stream().map(lang -> {
			return lang.toUpperCase();
		}).toList(); // Using multiple line in map() method.

		System.out.println(upperCaseNames1);
		System.out.println(upperCaseNames2);

	}
}

Output:

Method 1- [JAVA, PYTHON, GO]
Method 2- [JAVA, PYTHON, GO]

Key Points About map() in Stream API

✅ It is used for data transformation (e.g., modifying or converting objects).
✅ It does not modify the original collection; it creates a new stream.
✅ It is an intermediate operation (must be followed by a terminal operation like collect()).
✅ It can work with different data types, converting one type to another.

Leave a Reply

Your email address will not be published. Required fields are marked *