StreamAPI 提供了大量內建功能來幫助使用流管道。此 API 是聲明式程式設計,使程式碼更加精確且不易出錯。在Java 9中,Stream API中加入了一些有用的方法。
在下面的範例中,我們可以實作靜態方法:iterate()、takeWhile( )、 和Stream API 的dropWhile( ) 方法。
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>
以上是我們如何在Java 9中實作Stream API的方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!