Java Streams introduced in Java 8 provide a powerful and expressive way to process collections. One common use case is transforming or adding elements to an ArrayList
using a stream. This article walks through an example of how to add elements to an ArrayList
using Java Stream.
Example: Add to ArrayList in Stream
Here’s a simple Java example that shows how to use a stream to modify and add elements to a new ArrayList
.
java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamArrayListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Adding elements to ArrayList using stream
List<String> modifiedNames = names.stream()
.map(name -> name + " Smith")
.collect(Collectors.toCollection(ArrayList::new));
// Printing the modified ArrayList
System.out.println(modifiedNames);
}
}
Output:
csharp
[Alice Smith, Bob Smith, Charlie Smith]
Explanation:
- Original List: The list
names
contains three elements: "Alice"
, "Bob"
, and "Charlie"
. - Stream Transformation: Using
.stream()
, we convert the list into a stream and apply .map()
to transform each name by appending " Smith"
. - Collect to ArrayList: The transformed elements are collected into a new
ArrayList
using Collectors.toCollection(ArrayList::new)
. - Result: The new list
modifiedNames
contains the transformed names, and it is printed to the console.
When to Use This Pattern
- When you want to apply changes to each element in a list.
- When you're creating a new list based on transformations of another.
- When working with immutable or read-only lists, and you need a new, modified copy.
Summary
Java Streams make it easy and clean to manipulate lists. By using map()
and collect()
, you can efficiently add modified elements to a new ArrayList
. This approach improves readability and aligns with functional programming principles introduced in Java 8.