How to use IntSupplier in lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

An IntSupplier is a functional interface defined in "java.util.function" package. This interface represents an operation that takes without arguments and returns the result of int type. IntSupplier interface has only one method, getAsInt() and returns a result. This functional interface can be used as an assignment target for lambda expressions or method references.

Syntax

@FunctionalInterface
public interface IntSupplier {
   int getAsInt();
}

Example

import java.util.function.IntSupplier;

public class IntSupplierTest {
   public static void main(String[] args) {
      IntSupplier intSupplier1 = () -> Integer.MAX_VALUE;  // lamba expression
      System.out.println("The maximum value of an Integer is: " + intSupplier1.getAsInt());

      IntSupplier intSupplier2 = () -> Integer.MIN_VALUE;
      System.out.println("The minimum value of an Integer is: " + intSupplier2.getAsInt());

      int a = 10, b = 20;
      IntSupplier intSupplier3 = () -> a*b;
      System.out.println("The multiplication of a and b is: " + intSupplier3.getAsInt());
   }
}

Output

The maximum value of an Integer is: 2147483647
The minimum value of an Integer is: -2147483648
The multiplication of a and b is: 200
raja
Published on 03-Jan-2020 18:13:34
Advertisements