![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert an Iterable to Collection in Java
Let’s say the following is our Iterable −
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
Now, create a Collection −
Collection<Integer> c = convertIterable(i);
Above, we have a custom method convertIterable() for conversion. Following is the method −
public static <T> Collection<T> convertIterable(Iterable<T> iterable) { if (iterable instanceof List) { return (List<T>) iterable; } return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); }
Example
Following is the program to convert an Iterable to Collection in Java −
import java.util.*; import java.util.stream.*; public class Demo { public static <T> Collection<T> convertIterable(Iterable<T> iterable) { if (iterable instanceof List) { return (List<T>) iterable; } return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000); Collection<Integer> c = convertIterable(i); System.out.println("Collection (Iterable to Collection) = "+c); } }
Output
Collection (Iterable to Collection) = [50, 100, 150, 200, 250, 300, 500, 800, 1000]
Advertisements