StreamAPI provides a number of built-in functions to aid in working with stream pipes. The API is declarative programming, making the code more precise and less error-prone. In Java 9, some useful methods were added to the Stream API.
In the following example, we can implement static methods: iterate(), takeWhile( ), and dropWhile( of Stream API ) method.
import java.util.Arrays; import java.util.Iterator; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamAPITest { public static void main(String args[]) { String[] sortedNames = {"Adithya", "Bharath", "Charan", "Dinesh", "Raja", "Ravi", "Zaheer"}; System.out.println("[Traditional for loop] Indexes of names starting with R = "); for(int i = 0; i < sortedNames.length; i++) { if(sortedNames[i].<strong>startsWith</strong>("R")) { System.out.println(i); } } System.out.println("[Stream.iterate] Indexes of names starting with R = "); <strong>Stream.iterate</strong>(0, i -> i < sortedNames.length, i -> ++i).<strong>filter</strong>(i -> sortedNames[i].startsWith("R")).<strong>forEach</strong>(System.out::println); String namesAtoC = <strong>Arrays.stream</strong>(sortedNames).<strong>takeWhile</strong>(n -> n.<strong>charAt</strong>(0) <= 'C') .<strong>collect</strong>(Collectors.joining(",")); String namesDtoZ = <strong>Arrays.stream</strong>(sortedNames).<strong>dropWhile</strong>(n -> n.charAt(0) <= 'C') .<strong>collect</strong>(Collectors.joining(",")); System.out.println("Names A to C = " + namesAtoC); System.out.println("Names D to Z = " + namesDtoZ); } }
<strong>[Traditional for loop] Indexes of names starting with R = 4 5 [Stream.iterate] Indexes of names starting with R = 4 5 Names A to C = Adithya,Bharath,Charan Names D to Z = Dinesh,Raja,Ravi,Zaheer</strong>
The above is the detailed content of How can we implement methods of Stream API in Java 9?. For more information, please follow other related articles on the PHP Chinese website!