reduce method of Stream class

  • reduce is an aggregating method that aggregates the output into a single value
  • stream class has 3 variant of reduce method for which return types of each is different
    • Optional reduce(BinaryOperator accumulator);
    • T reduce(T identity, BinaryOperator<T> accumulator);
    • <U> U reduce(U identity,BiFunction<U, ? super T> accumulator,BinaryOperator<U> combiner);

Example :

Example :

map method of Stream class

  • Java 8 Stream’s map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream.
  • It simply used to convert Stream of one type to another.
  •  signature of Stream’s map method.
    • <R> Stream<R> map(Function<? super T,? extends R>mapper)
  • Types of map method in Stream class
    • map()
    • mapToInt()
    • mapToLong()
    • mapToDouble()
Stream map

Java 8 Supplier

  • Stream's generate method returns an infinite sequential stream where supplier generates each element.
  • Following are the primitive Specializations for Supplier interface in java.util.function package.
    • IntSupplier  – Represents a supplier of int-valued results. Having one method getAsInt().
    • LongSupplier – Represents a supplier of long-valued results. Having one method getAsLong().
    • DoubleSupplier – Represents a supplier of double-valued results. Having one method getAsDouble().
    • BooleanSupplier  – Represents a supplier of boolean-valued results. Having one method getAsBoolean().

Syntax :

  • Let’s say you want to generate 5 random numbers between 0 to 10.
  • Stream's generate method returns an infinite sequential stream where supplier generates each element.

Example :

Example: Returns a supplier

Example: Factory

Optional class

  • Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. 
  • By using Optional, we can specify alternate values to return or alternate code to run.
  • This makes the code more readable because the facts which were hidden are now visible to the developer.

Practical User :

  • We can easily make a null check on findFirst and find any using orElse method of optional
    • T orElse(T other)


  • T orElse(T other)
    • Checks if an optional is null, if yes return other else return value
    • This value is a single value returned via findFirst() or findAny() of steam method
  • T get()
    • If a value is present in this {@code Optional}, returns the value,
    • otherwise throws NoSuchElementException
    • Hence isPresent() method value should be used before get
    • This method is similar to orElse but no null check or alternative value hear
  • boolean isPresent()
    • Return true if there is a value present, otherwise returns false