Home  >  Article  >  Java  >  What is the difference between takewhile() and dropWhile() methods in Java 9?

What is the difference between takewhile() and dropWhile() methods in Java 9?

WBOY
WBOYforward
2023-09-01 20:57:031380browse

Java 9中takewhile()和dropWhile()方法的区别是什么?

Stream API’s takewhile() method accepts all values ​​until predicate returns false, And Stream API's >dropWhile() method will delete all values ​​until it matches the predicate . If the stream is ordered, the takewhile() method returns a stream containing the longest prefix## of the elements taken from this stream that match the predicate #, while the dropWhile() method returns the remaining stream after matching the predicate. If the stream is unordered, the takewhile() method returns a stream consisting of a subset of elements taken from the stream matching the given predicate, while dropWhile() Method returns the stream consisting of the remaining elements of the stream after removing the subset of elements matching the given predicate.

The syntax of takeWhile()

<strong>default Stream<T> takeWhile(Predicate<? super T><!--? super T--> predicate)</strong>

Example

import java.util.stream.Stream;
public class TakeWhileMethodTest {
   public static void main(String args[]) {
      <strong>Stream</strong>.<strong>of</strong>("India", "Australia", "Newzealand", "", "South Africa", "England")
      .<strong>takeWhile</strong>(o->!o.isEmpty())
      .forEach(System.out::print);
   }
}

Output

<strong>IndiaAustraliaNewzealand
</strong>

dropWhile() syntax

<strong>default Stream<T> dropWhile(Predicate<? super T><!--? super T--> predicate)</strong>

Example

import java.util.stream.Stream;
public class DropWhileMethodTest {
   public static void main(String args[]) {
      <strong>Stream</strong>.<strong>of</strong>("India", "Australia", "Newzealand", "", "England", "Srilanka")
      .<strong>dropWhile</strong>(o->!o.isEmpty())
      .forEach(System.out::print);
      System.out.println();
      <strong>Stream</strong>.<strong>of</strong>("India", "", "Australia", "", "England", "Srilanka")
      .<strong>dropWhile</strong>(o->!o.isEmpty())
      .forEach(System.out::print);
   }
}

Output

<strong>EnglandSrilanka
AustraliaEnglandSrilanka</strong>

The above is the detailed content of What is the difference between takewhile() and dropWhile() methods 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