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:
Convert an Iterable to Collection in Java
Next article icon

Convert an Iterable to Collection in Java

Last Updated : 28 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
But at certain times, it is required to switch from iterable to collection and vice versa. For more details on difference between Iterable and Collection, please refer to the post Iterator vs Collection in Java.
The conversion of Iterable to Collection can be carried out in following ways:
 

  • Creating a utility function: Creating a utility function means creating a function that converts the iterable to a collection by explicitly taking each item into account. This also can be done in many ways as explained below: 
    • Using For loop
Java
// Below is the program to convert an Iterable // into a Collection using for loop  import java.io.*; import java.util.*;  class GFG {     // function to convert Iterable into Collection     public static <T> Collection<T>                     getCollectionFromIterable(Iterable<T> itr)     {         // Create an empty Collection to hold the result         Collection<T> cltn = new ArrayList<T>();          // Iterate through the iterable to         // add each element into the collection         for (T t : itr)             cltn.add(t);          // Return the converted collection         return cltn;     }      public static void main(String[] args)     {         Iterable<Integer> i = Arrays.asList(1, 2, 3, 4);         System.out.println("Iterable List : " + i);          Collection<Integer> cn = getCollectionFromIterable(i);         System.out.println("Collection List : " + cn);     } } 

Output: 
Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4]

 
  • Using Iterable.forEach(): 
    It can be used in Java 8 and above.
Java
// Below is the program to convert an Iterable // into a Collection using iterable.forEach  import java.io.*; import java.util.*;  class GFG {     // function to convert Iterable into Collection     public static <T> Collection<T>                  getCollectionFromIterable(Iterable<T> itr)     {         // Create an empty Collection to hold the result         Collection<T> cltn = new ArrayList<T>();          // Use iterable.forEach() to         // Iterate through the iterable and         // add each element into the collection         itr.forEach(cltn::add);          // Return the converted collection         return cltn;     }      public static void main(String[] args)     {         Iterable<Integer> i = Arrays.asList(1, 2, 3, 4);         System.out.println("Iterable List : " + i);          Collection<Integer> cn = getCollectionFromIterable(i);         System.out.println("Collection List : " + cn);     } } 

Output: 
Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4]

 
  • Using Iterator: The forEach loop uses Iterator in the background. Hence it can be done explicitly in the following way.
Java
// Below is the program to convert an Iterable // into a Collection using Iterator  import java.io.*; import java.util.*;  class GFG {     // function to convert Iterable into Collection     public static <T> Collection<T>                     getCollectionFromIterable(Iterable<T> itr)     {         // Create an empty Collection to hold the result         Collection<T> cltn = new ArrayList<T>();          // Get the iterator at the iterable         Iterator<T> iterator = itr.iterator();          // Iterate through the iterable using         // iterator to add each element into the collection         while (iterator.hasNext()) {             cltn.add(iterator.next());         }          // Return the converted collection         return cltn;     }      public static void main(String[] args)     {         Iterable<Integer> i = Arrays.asList(1, 2, 3, 4);         System.out.println("Iterable List : " + i);          Collection<Integer> cn = getCollectionFromIterable(i);         System.out.println("Collection List : " + cn);     } } 

Output: 
Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4]

 
  • Java 8 Stream: With the introduction of Stream in Java 8, works like this has become quite easy. To convert iterable to Collection, the iterable is first converted into spliterator. Then with the help of StreamSupport.stream(), the spliterator can be traversed and then collected with the help collect() into collection.
Java
// Program to convert an Iterable // into a Collection  import java.io.*; import java.util.*; import java.util.stream.*;  class GFG {     // function to convert Iterable into Collection     public static <T> Collection<T>                     getCollectionFromIterable(Iterable<T> itr)     {         // Create an empty Collection to hold the result         Collection<T> cltn = new ArrayList<T>();          return StreamSupport.stream(itr.spliterator(), false)             .collect(Collectors.toList());     }      public static void main(String[] args)     {         Iterable<Integer> i = Arrays.asList(1, 2, 3, 4);         System.out.println("Iterable List : " + i);          Collection<Integer> cn = getCollectionFromIterable(i);         System.out.println("Collection List : " + cn);     } } 

Output: 
Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4]

 

Next Article
Convert an Iterable to Collection in Java

R

RishabhPrabhu
Improve
Article Tags :
  • Misc
  • Java
  • Java-Collections
Practice Tags :
  • Java
  • Java-Collections
  • Misc

Similar Reads

    Convert an Iterable to Stream in Java
    Given an Iterable, the task is to convert it into Stream in Java. Examples: Input: Iterable = [1, 2, 3, 4, 5] Output: {1, 2, 3, 4, 5} Input: Iterable = ['G', 'e', 'e', 'k', 's'] Output: {'G', 'e', 'e', 'k', 's'} Approach: Get the Iterable. Convert the Iterable to Spliterator using Iterable.spliterat
    1 min read
    Convert an Iterator to a List in Java
    Given an Iterator, the task is to convert it into List in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Below are the various ways to do so: Naive Approach: Get the Iterator. Create an empty lis
    2 min read
    Collection Interface in Java
    The Collection interface in Java is a core member of the Java Collections Framework located in the java.util package. It is one of the root interfaces of the Java Collection Hierarchy. The Collection interface is not directly implemented by any class. Instead, it is implemented indirectly through it
    6 min read
    Convert Iterator to Iterable in Java
    Given an Iterator, the task is to convert it into Iterables in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Below are the various ways to do so: By overriding the abstract method Iterable.itera
    3 min read
    Iterator vs Collection in Java
    Iterator and Collection, both has helped and comforted the programmers at many a times. But their usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iteratorIterators are used in Collection fr
    3 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