Java Streams - ashish-ghub/docs GitHub Wiki

Java 8 introduced several important functional interfaces in the java.util.function package that serve as the building blocks for functional programming and lambda expressions. Here are the main functional interfaces provided by Java 8:

Consumer:

Interface: Consumer Represents an operation that accepts a single input argument and returns no result. Contains the method. void accept(T t)

Predicate:

Interface: Predicate Represents a boolean-valued function that takes an argument of type T and returns a boolean. Contains the method boolean test(T t)

Function:

Interface: Function<T, R> Represents a function that takes an argument of type T and returns a result of type R. Contains the R apply(T t) method.

Supplier:

Interface: Supplier

Represents a supplier of results (values) of type T.

Contains the method T get()

UnaryOperator:

Interface: UnaryOperator Represents an operation on a single operand that produces a result of the same type as the operand. Extends Function<T, T>.

BinaryOperator:

Interface: BinaryOperator Represents an operation upon two operands of the same type, producing a result of the same type as the operands. Extends BiFunction<T, T, T>

BiConsumer:

Interface: BiConsumer<T, U> Represents an operation that accepts two input arguments and returns no result. Contains the void accept(T t, U u) method.

BiPredicate:

Interface: BiPredicate<T, U> Represents a boolean-valued function that takes two arguments of types T and U and returns a boolean. Contains the method boolean test(T t, U u)

BiFunction:

Interface: BiFunction<T, U, R> Represents a function that takes two arguments of types T and U and returns a result of type R. Contains the R apply(T t, U u) method. These functional interfaces provide a way to work with lambda expressions and streams more effectively and expressively. They are the foundation of Java's functional programming capabilities introduced in Java 8.

Java Optional:

https://www.oracle.com/technical-resources/articles/java/java8-optional.html

Issue with null check to get some value:

String version = "UNKNOWN";
if(computer != null){
   Soundcard soundcard = computer.getSoundcard();
   if(soundcard != null){
      USB usb = soundcard.getUSB();
        if(usb != null){
          version = usb.getVersion();
    }
 }

How to fix it :

 public class Computer {
   private Optional<Soundcard> soundcard;   
   public Optional<Soundcard> getSoundcard() { ... }
   ...
 }

public class Soundcard {
  private Optional<USB> usb;
  public Optional<USB> getUSB() { ... }
}

public class USB{
  public String getVersion(){ ... }
}

Better code with this:

String name = computer.flatMap(Computer::getSoundcard)
                          .flatMap(Soundcard::getUSB)
                          .map(USB::getVersion)
                          .orElse("UNKNOWN");
⚠️ **GitHub.com Fallback** ⚠️