3 Ways to Convert Java 8 Stream to an Array - Lambda Expression and Constructor Reference Example

One of the frequently asked Java 8 questions is, how you do convert a Java 8 Stream to an array? For example, you have a Stream of Strings and you want an array of String so that you can pass this to a legacy method which expects an array, how do you do that? Well, the obvious place to search is the Javadoc of java.util.stream.Stream class and there you will find a toArray() method. Though this method will convert the Stream to an array it has a problem, it returns an Object array. What will you do, if you need a String array? Well, you can use the overloaded version of toArray(IntFunction generator), which expect a generator function to create an array of specified type. You can pass a lambda expression or constructor reference to this method to specify the type of array you want. This will return you an array of T i.e. if String contains String then it will return String array.
Read more �

Posting Komentar

0 Komentar