Programming & Development / April 12, 2025

How to Add to ArrayList Using Java Stream – Example Explained

Java Stream add to ArrayList Java Stream example ArrayList transformation collect to ArrayList Java 8 stream map in stream ArrayList in Java

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:

  1. Original List: The list names contains three elements: "Alice", "Bob", and "Charlie".
  2. Stream Transformation: Using .stream(), we convert the list into a stream and apply .map() to transform each name by appending " Smith".
  3. Collect to ArrayList: The transformed elements are collected into a new ArrayList using Collectors.toCollection(ArrayList::new).
  4. 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.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex