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

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

王林
王林forward
2023-08-25 14:45:02697browse

我们如何在Java 9中实现Stream API的方法?

StreamAPI provides a number of built-in functions to aid in working with stream pipes. The API is declarative programming, making the code more precise and less error-prone. In Java 9, some useful methods were added to the Stream API.

  • Stream.iterate(): This method can be used as an alternative to the stream version of the traditional for loop.
  • Stream.takeWhile(): This method can be used in a while loop to take the value when the condition is met.
  • Stream.dropWhile(): This method can delete the value in the while loop when the condition is met.

In the following example, we can implement static methods: iterate(), takeWhile( ), and dropWhile( of Stream API ) method.

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) <= &#39;C&#39;)
.<strong>collect</strong>(Collectors.joining(","));

      String namesDtoZ = <strong>Arrays.stream</strong>(sortedNames).<strong>dropWhile</strong>(n -> n.charAt(0) <= &#39;C&#39;)
.<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>

The above is the detailed content of How can we implement methods of Stream API in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete