
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Java Array to Iterable
To make an array iterable either you need to convert it to a stream or as a list using the asList() or stream() methods respectively. Then you can get an iterator for these objects using the iterator() method.
Example
import java.util.Arrays; import java.util.Iterator; public class ArrayToIterable { public static void main(String args[]){ Integer[] myArray = {897, 56, 78, 90, 12, 123, 75}; Iterator<Integer> iterator = Arrays.stream(myArray).iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output
897 56 78 90 12 123 75
As mentioned above, you can also convert an array to list and get an iterator from that list using the iterator() method.
Integer[] myArray = {897, 56, 78, 90, 12, 123, 75}; Iterator<Integer> iterator = Arrays.asList(myArray).iterator(); //Iterator<Integer> iterator = Arrays.stream(myArray).iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); }
Advertisements