Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Flatten a Stream of Lists in Java using forEach loop
Next article icon

Flatten a Stream of Lists in Java using forEach loop

Last Updated : 11 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples:
  Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ]  Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]    Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ]   Output: [G, e, e, k, s, F, o, r]  
Approach:
  1. Get the Lists in the form of 2D list.
  2. Create an empty list to collect the flattened elements.
  3. With the help of forEach loop, convert each elements of the list into stream and add it to the list
  4. Now convert this list into stream using stream() method.
  5. Now flatten the stream by converting it into list using collect() method.
Below is the implementation of the above approach: Example 1: Using lists of integer. Java
// Java program to flatten a stream of lists // using forEach() method  import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.*;  class GFG {      // Function to flatten a Stream of Lists     public static <T> Stream<T> flattenStream(List<List<T> > lists)     {          // Create an empty list to collect the stream         List<T> finalList = new ArrayList<>();          // Using forEach loop         // convert the list into stream         // and add the stream into list         for (List<T> list : lists) {             list.stream()                 .forEach(finalList::add);         }          // Convert the list into Stream and return it         return finalList.stream();     }      public static void main(String[] args)     {          // Get the lists to be flattened.         List<Integer> a = Arrays.asList(1, 2);         List<Integer> b = Arrays.asList(3, 4, 5, 6);         List<Integer> c = Arrays.asList(7, 8, 9);          List<List<Integer> > arr = new ArrayList<List<Integer> >();         arr.add(a);         arr.add(b);         arr.add(c);          // Flatten the Stream         List<Integer> flatList = new ArrayList<Integer>();         flatList = flattenStream(arr)                        .collect(Collectors.toList());          // Print the flattened list         System.out.println(flatList);     } } 
Output:
  [1, 2, 3, 4, 5, 6, 7, 8, 9]  
Example 2: Using lists of Characters. Java
// Java program to flatten a stream of lists // using forEach() method  import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.*;  class GFG {      // Function to flatten a Stream of Lists     public static <T> Stream<T> flattenStream(List<List<T> > lists)     {          // Create an empty list to collect the stream         List<T> finalList = new ArrayList<>();          // Using forEach loop         // convert the list into stream         // and add the stream into list         for (List<T> list : lists) {             list.stream()                 .forEach(finalList::add);         }          // Convert the list into Stream and return it         return finalList.stream();     }      public static void main(String[] args)     {          // Get the lists to be flattened.         List<Character> a = Arrays.asList('G', 'e', 'e', 'k', 's');         List<Character> b = Arrays.asList('F', 'o', 'r');         List<Character> c = Arrays.asList('G', 'e', 'e', 'k', 's');          List<List<Character> > arr = new ArrayList<List<Character> >();         arr.add(a);         arr.add(b);         arr.add(c);          // Flatten the Stream         List<Character> flatList = new ArrayList<Character>();         flatList = flattenStream(arr)                        .collect(Collectors.toList());          // Print the flattened list         System.out.println(flatList);     } } 
Output:
  [G, e, e, k, s, F, o, r, G, e, e, k, s]  

Next Article
Flatten a Stream of Lists in Java using forEach loop

R

RishabhPrabhu
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Flatten a Stream of Map in Java using forEach loop
    Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get
    3 min read
    Flatten a Stream of Arrays in Java using forEach loop
    Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach:
    3 min read
    Stream forEach() method in Java with examples
    Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer<? super T> action) Where, Consumer is a functional int
    2 min read
    Stream forEachOrdered() method in Java with examples
    Stream forEachOrdered(Consumer action) performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. Stream forEachOrdered(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-ef
    2 min read
    Difference between Stream.of() and Arrays.stream() method in Java
    Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example:  Java // Java program to demo
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences