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中文网其他相关文章!