In Java, List.stream().map()
is a powerful combination of methods used to transform elements in a list using the Stream API. Let's break down what each part does:
List
A List
in Java is an ordered collection (also known as a sequence). The List
interface provides a way to store elements and access them by their index. It is a part of the Java Collections Framework and can be implemented by various classes like ArrayList
, LinkedList
, etc.
stream()
The stream()
method is a default method of the Collection
interface, and since List
is a sub-interface of Collection
, all List instances can use this method. The stream()
method returns a sequential Stream with the elements of the list as its source. A Stream
represents a sequence of elements on which one or more operations can be performed.
map()
The map()
method is an intermediate operation of the Stream interface. It takes a Function
as an argument and applies this function to each element of the stream, producing a new stream with the transformed elements.
Combining List.stream().map()
When you combine List.stream()
with .map()
, you are essentially creating a stream from a list and then transforming each element of that list using a specified function.
Here is a concrete example to illustrate this:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List<String> strings = Arrays.asList("a", "b", "c", "d");
// Using List.stream().map() to transform elements
List<String> upperCaseStrings = strings.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upperCaseStrings); // Output: [A, B, C, D]
}
}
In this example:
Arrays.asList("a", "b", "c", "d")
creates a list of strings.strings.stream()
converts the list into a stream.map(String::toUpperCase)
applies thetoUpperCase
method to each element of the stream, transforming each string to its uppercase equivalent.collect(Collectors.toList())
collects the transformed elements into a new list.
The result is that the original list of lowercase strings is transformed into a list of uppercase strings.
Summary
List
: A collection of elements.stream()
: Converts the list into a stream.map()
: Applies a function to each element of the stream, transforming it.- Example:
List.stream().map()
is used to create a stream from a list and apply a transformation function to each element, resulting in a new stream of transformed elements. This new stream can then be collected back into a list or another collection if needed.