Java streams 16. Filtering, Skipping, Sorting

  • Stream<T> distinct(). Compares stream elements using method Object.equals(Object) and skips the duplicates.
  • Stream<T> filter(Predicate<T> predicate). Allows flowing downstream only those elements that result in true when processed by the provided Predicate function.
  • default Stream<T> dropWhile(Predicate<T> predicate). Skips those first elements of the stream that result in true when processed by the provided Predicate function
  • default Stream<T> takeWhile(Predicate<T> predicate). Allows only those first elements of the stream to be processed that result in true when processed by the provided Predicate function
Stream.of("2", "4", "3", "4", "2")
.distinct()
.forEach(System.out::print); //prints: 243
Stream.of("2", "4", "3", "4", "2")
.filter(s -> Objects.equals(s, "2"))
.forEach(System.out::print); //prints: 22
Stream.of("2", "4", "3", "4", "2")
.dropWhile(s -> Integer.valueOf(s) < 3)
.forEach(System.out::print); //prints: 4342
Stream.of("2", "4", "3", "4", "2")
.takeWhile(s -> Integer.valueOf(s) < 3)
.forEach(System.out::print); //prints: 2
  • Stream<T> skip(long n). Ignores the first n stream elements emitted by the Stream object.
  • Stream<T> limit(long n). Allows only the first n stream elements emitted by the Stream object to flow downstream.
Stream.of("2", "4", "3", "4", "2")
.skip(3)
.forEach(System.out::print); //prints: 42
Stream.of("2", "4", "3", "4", "2")
.limit(3)
.forEach(System.out::print); //prints: 243
  • Stream<T> sorted(). Sorts the stream elements in the natural order (according to
    their implementation of the Comparable interface).
  • Stream<T> sorted(Comparator<T> comparator). Sorts the stream elements in the
    order according to the provided Comparator<T> object.
Stream.of("2", "4", "3", "4", "2")
.sorted().forEach(System.out::print); //prints: 22344
Stream.of("2", "4", "3", "4", "2")
.sorted(Comparator.reverseOrder())
.forEach(System.out::print); //prints: 44322

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nick Samoylov

Nick Samoylov

49 Followers

Born in Moscow, lived in Crimea, now lives in the US. Used to be physicist and rock climber, now programmer and writer.