
StreamAPI 提供了大量内置功能来帮助使用流管道。该 API 是声明式编程,使代码更加精确且不易出错。在Java 9中,Stream API中添加了一些有用的方法。
- Stream.iterate() :此方法可以用作传统for循环的流版本替代。
- Stream.takeWhile():此方法可以在 while 循环中使用,在满足条件时取值。
- Stream.dropWhile():此方法可以在while 循环在满足条件时删除值。
在下面的示例中,我们可以实现静态方法: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>











