Stream API cung cấp nhiều chức năng built-in giúp thực hiện operation trên collection dùng stream pipeline. API là declarative programming làm code chính xác và ít lỗi hơn. Trong Java 9, thêm vài method hữu ích vào Stream API.
- Stream.iterate(): Dùng như stream version thay thế for-loop truyền thống.
- Stream.takeWhile(): Dùng trong while loop lấy giá trị khi điều kiện thỏa mãn.
- Stream.dropWhile(): Dùng trong while loop bỏ giá trị khi điều kiện thỏa mãn.
Ví dụ dưới triển khai static method: iterate(), takeWhile(), dropWhile() của Stream API.
Ví dụ
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);
}
}
Kết quả
[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