Stream API提供了许多内置功能, 以帮助使用流管道对集合执行操作。该API是声明式编程 ,可使代码更加精确且不易出错。在Java 9中,很少有有用的方法添加到Stream API中。
Stream.iterate():此方法可用作传统for循环的流版本替换。
Stream.takeWhile():此方法可以在while循环中使用,该循环在满足条件时会取值 。
Stream.dropWhile():此方法可以在while循环中使用,该循环在满足条件时会丢弃值 。
在下面的例子中,我们可以实现静态方法: 迭代() takeWhile()
,和dropWhile()方法的流API。
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].startsWith("R")) { System.out.println(i); } } System.out.println("[Stream.iterate] Indexes of names starting with R = "); Stream.iterate(0, i -> i < sortedNames.length, i -> ++i).filter(i -> sortedNames[i].startsWith("R")).forEach(System.out::println); String namesAtoC = Arrays.stream(sortedNames).takeWhile(n -> n.charAt(0) <= 'C') .collect(Collectors.joining(",")); String namesDtoZ = Arrays.stream(sortedNames).dropWhile(n -> n.charAt(0) <= 'C') .collect(Collectors.joining(",")); System.out.println("Names A to C = " + namesAtoC); System.out.println("Names D to Z = " + namesDtoZ); } }
输出结果
[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