- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differences between takewhile() and dropWhile() methods in Java 9?
The takewhile() method of Stream API accepts all values until predicate returns false whereas dropWhile() method of Stream API drops all values until it matches the predicate. If a stream is ordered, the takewhile() method returns a stream consisting of the longest prefix of elements taken from this stream that matches predicate whereas the dropWhile() method returns the remaining stream after matching predicate. If the stream is unordered, the takewhile() method returns a stream consisting of a subset of elements extracted from a stream that matches the given predicate whereas the dropWhile() method returns a stream consisting of the remaining elements of a stream after dropping a subset of elements that matches the given predicate.
Syntax of takeWhile()
default Stream<T> takeWhile(Predicate<? super T> predicate)
Example
import java.util.stream.Stream; public class TakeWhileMethodTest { public static void main(String args[]) { Stream.of("India", "Australia", "Newzealand", "", "South Africa", "England") .takeWhile(o->!o.isEmpty()) .forEach(System.out::print); } }
Output
IndiaAustraliaNewzealand
Syntax of dropWhile()
default Stream<T> dropWhile(Predicate<? super T> predicate)
Example
import java.util.stream.Stream; public class DropWhileMethodTest { public static void main(String args[]) { Stream.of("India", "Australia", "Newzealand", "", "England", "Srilanka") .dropWhile(o->!o.isEmpty()) .forEach(System.out::print); System.out.println(); Stream.of("India", "", "Australia", "", "England", "Srilanka") .dropWhile(o->!o.isEmpty()) .forEach(System.out::print); } }
Output
EnglandSrilanka AustraliaEnglandSrilanka
Advertisements