Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java 8 FAQ: Top Questions

15. What is the purpose of the map() method in Java 8 Streams?

The map() method is an intermediate operation in the Java 8 Stream API that applies a transformation function to each element of the stream. It is used to convert elements from one form to another.

πŸ—ΊοΈ Step-by-Step Instructions:

  1. Use map() to apply a function to every element in the stream.
  2. Each input element is transformed individually and returns a new stream.
  3. Common transformations include converting data types, applying business rules, or formatting output.

πŸ“₯ Example Input:

List names = Arrays.asList("alice", "bob", "claire");

List uppercased = names.stream()
                               .map(String::toUpperCase)
                               .collect(Collectors.toList());

πŸ† Expected Output:

[ALICE, BOB, CLAIRE]

βœ… Java 8 Solution:

import java.util.*;
import java.util.stream.*;

public class StreamMapExample {
  public static void main(String[] args) {
    List names = Arrays.asList("alice", "bob", "claire");

    List uppercased = names.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());

    System.out.println(uppercased);
  }
}

πŸ“˜ Detailed Explanation:

  • map(): Applies a transformation function to each element.
  • Returns: A new stream with the transformed elements.
  • Common usage: Formatting strings, converting types, applying computations.

πŸ› οΈ Use Cases:

  • Converting numeric values (e.g., from int to double).
  • Formatting names or data before display.
  • Applying business logic transformations in a clean way.