Convert Java Array to Iterable
In this article, we will explore different approaches to convert a Java array to an Iterable object. We will cover various methods, including using the Stream API, Apache Commons Lang, and Guava libraries. Each method will be accompanied by code examples to illustrate the conversion process. By the end of this tutorial, you will have a clear understanding of how to convert a Java array to an Iterable object and will be able to choose the most suitable method for your specific requirements.
1. Introduction
In Java, arrays are a fundamental data structure that allows you to store multiple elements of the same type. However, arrays are not directly compatible with the Iterable interface, which is commonly used in Java to iterate over a collection of elements. This limitation can be overcome by converting the array into an Iterable object, which provides enhanced flexibility and compatibility with various Java APIs.
Before diving into the conversion techniques, let’s briefly discuss the Iterable interface and its significance in Java. The Iterable interface is a part of the Java Collections Framework and is implemented by classes that represent a collection of elements. It provides a standard way to traverse and iterate over the elements in a collection.
To convert a Java array to an Iterable object, we need to create a custom implementation that adheres to the Iterable interface’s contract. This can be achieved using different methods, as we will explore in the following sections.
2. Using Stream API collect()
The Stream API, introduced in Java 8, provides a functional programming approach for processing collections of data. It offers a powerful set of operations, including filtering, mapping, and reducing elements. One of the operations provided by the Stream API is the collect()
method, which can be used to convert a Stream to various data structures, including Iterable objects.
To convert a Java array to an Iterable object using the Stream API’s collect()
method, we can follow these steps:
- Create a Stream from the array using the
Arrays.stream()
method. - Use the
collect()
method, specifyingCollectors.toList()
as the collector. - Wrap the resulting List in a custom implementation of the Iterable interface.
Here’s an example that demonstrates this conversion process:
import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; public class ArrayToIterableExample { public static <T> Iterable<T> convertArrayToIterable(T[] array) { List<T> list = Arrays.stream(array).collect(Collectors.toList()); return new Iterable<T>() { @Override public Iterator<T> iterator() { return list.iterator(); } }; } public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Orange"}; Iterable<String> iterable = convertArrayToIterable(fruits); for (String fruit : iterable) { System.out.println(fruit); } } }
In this example, the convertArrayToIterable()
method takes a generic array as input and returns an Iterable object. The array is first converted to a List using the collect(Collectors.toList())
operation. Then, an anonymous implementation of the Iterable interface is created, which uses the List’s iterator to provide iteration functionality.
When the main()
method is executed, the fruits
array is converted to an Iterable object using the convertArrayToIterable()
method. The resulting Iterable object is then used in a foreach loop to iterate over the elements and print them.
3. Using Stream API iterator()
Another approach to convert a Java array to an Iterable object is by directly implementing the Iterator interface using the Stream API’s iterator()
method. This method allows us to create a custom Iterator object that can iterate over the elements of a Stream.
To convert a Java array to an Iterable object using the Stream API’s iterator()
method, we can follow these steps:
- Create a Stream from the array using the
Arrays.stream()
method. - Use the
iterator()
method to obtain an Iterator object. - Wrap the Iterator object in a custom implementation of the Iterable interface.
Let’s take a look at an example:
import java.util.Arrays; import java.util.Iterator; import java.util.stream.Stream; public class ArrayToIterableExample { public static <T> Iterable<T> convertArrayToIterable(T[] array) { Stream<T> stream = Arrays.stream(array); Iterator<T> iterator = stream.iterator(); return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } public static void main(String[] args) { Integer[] numbers = {1, 2, 3, 4, 5}; Iterable<Integer> iterable = convertArrayToIterable(numbers); for (Integer number : iterable) { System.out.println(number); } } }
In this example, the convertArrayToIterable()
method takes a generic array as input and returns an Iterable object. The array is first converted to a Stream using the Arrays.stream()
method. Then, the iterator()
method is called on the Stream to obtain an Iterator object. Finally, an anonymous implementation of the Iterable interface is created, which uses the obtained Iterator to provide iteration functionality.
When the main()
method is executed, the numbers
array is converted to an Iterable object using the convertArrayToIterable()
method. The resulting Iterable object is then used in a foreach loop to iterate over the elements and print them.
4. Using Apache Commons Lang ArrayUtils
Apache Commons Lang is a widely used library that provides a variety of utility classes and methods for common programming tasks. The ArrayUtils class in Apache Commons Lang offers convenient methods for manipulating and working with arrays, including converting arrays to Iterable objects.
First, we need to add the dependency commons-lang3
:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
To convert a Java array to an Iterable object using Apache Commons Lang, we can use the ArrayUtils.toObject()
method in conjunction with the Arrays.asList() method. Here’s an example:
import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; public class ArrayToIterableExample { public static <T> Iterable<T> convertArrayToIterable(T[] array) { T[] boxedArray = ArrayUtils.toObject(array); return Arrays.asList(boxedArray); } public static void main(String[] args) { Double[] prices = {10.99, 19.99, 5.99}; Iterable<Double> iterable = convertArrayToIterable(prices); for (Double price : iterable) { System.out.println(price); } } }
In this example, the convertArrayToIterable()
method takes a generic array as input and returns an Iterable object. The ArrayUtils.toObject()
method is used to convert the array to its boxed equivalent. Then, the Arrays.asList()
method is called to create a List from the boxed array, which implements the Iterable interface.
When the main()
method is executed, the prices
array is converted to an Iterable object using the convertArrayToIterable()
method. The resulting Iterable object is then used in a foreach loop to iterate over the elements and print them.
5. Using Guava
Guava is a popular open-source library developed by Google that provides a rich set of utility classes and methods for Java programming. It offers various collection-related utilities, including methods to convert arrays to Iterable objects.
To convert a Java array to an Iterable object using Guava, we can use the com.google.common.primitives
package, which provides utility methods for working with primitive arrays. The asList()
method in this package can be used to convert a primitive array to a List, which implements the Iterable interface.
First, let’s add the dependency:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>32.0.1-jre</version> </dependency>
Here’s an example:
import com.google.common.primitives.Ints; import java.util.List; public class ArrayToIterableExample { public static Iterable<Integer> convertArrayToIterable(int[] array) { List<Integer> list = Ints.asList(array); return list; } public static void main(String[] args) { int[] temperatures = {25, 28, 30, 26, 27}; Iterable<Integer> iterable = convertArrayToIterable(temperatures); for (Integer temperature : iterable) { System.out.println(temperature); } } }
In this example, the convertArrayToIterable()
method takes an int array as input and returns an Iterable object. The Ints.asList()
method from the Guava library is used to convert the int array to a List of Integer objects. The List implements the Iterable interface, allowing it to be used as an Iterable object.
When the main()
method is executed, the temperatures
array is converted to an Iterable object using the convertArrayToIterable()
method. The resulting Iterable object is then used in a foreach loop to iterate over the elements and print them.
6. Conclusion
In this tutorial, we explored various methods to convert a Java array to an Iterable object. We discussed using the Stream API’s collect()
and iterator()
methods, Apache Commons Lang’s ArrayUtils, and Guava’s utility methods. Each method has its own advantages and may be more suitable depending on the specific requirements of your application.
By converting a Java array to an Iterable object, you can leverage the power of the Iterable interface and easily integrate with other Java APIs that expect iterable collections. Whether you choose to use the Stream API, Apache Commons Lang, Guava, or any other approach, you now have the knowledge to transform arrays into iterable structures efficiently.
7. Download the Source Code
This was an example of how to Convert Java Array to Iterable.
You can download the full source code of this example here: Convert Java Array to Iterable