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>
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); } }
<strong>IndiaAustraliaNewzealand </strong>
dropWhile() syntax
<strong>default Stream<T> dropWhile(Predicate<? super T><!--? super T--> predicate)</strong>
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); } }
<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!