Tampilkan postingan dengan label Stream API examples. Tampilkan semua postingan
Tampilkan postingan dengan label Stream API examples. Tampilkan semua postingan

Minggu, 08 Januari 2017

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 �

Sabtu, 26 Maret 2016

In Java 8, you can use the Stream.findFirst() method to get the first element of Stream in Java. This is a terminal operation and often used after applying several intermediate operations e.g. filter, mapping, flattening etc. For example, if you have a List of String and you want to find the first String whose length is greater than 10, you can use the findFirst() method along with stream() and filter() to get that String. The stream() method gets the Stream from a List, which then allow you to apply several useful methods defined in the java.util.Stream class e.g. filter(), map(), flatMap() etc.
Read more �