Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-09-01 20:57:03
forward
1364 people have browsed it

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>
Copy after login

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);
   }
}
Copy after login

Output

<strong>IndiaAustraliaNewzealand
</strong>
Copy after login

dropWhile() syntax

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

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);
   }
}
Copy after login

Output

<strong>EnglandSrilanka
AustraliaEnglandSrilanka</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template