Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can we implement methods of Stream API in Java 9?
Stream API provides lots of built-in functionality to help in performing operations on a collection using a stream pipeline. The API is declarative programming that makes the code precise and less error-prone. In Java 9, few useful methods have added to Stream API.
- Stream.iterate(): This method can be been used as stream version replacement for traditional for-loops.
- Stream.takeWhile(): This method can be used in a while loop that takes value while the condition is met.
- Stream.dropWhile(): This method can be used in a while loop that drops value while the condition is met.
In the below example, we can implement the static methods: iterate(), takeWhile(), and dropWhile() methods of Stream API.
Example
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);
}
}
Output
<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>
Advertisements
