Differences between takewhile() and dropWhile() methods in Java 9?

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 17-Feb-2020 07:22:42
Advertisements