How can we implement methods of Stream API in Java 9?

JavaObject Oriented ProgrammingProgramming

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].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);
   }
}

Output

[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
raja
Published on 15-Apr-2020 21:25:40
Advertisements