Java Lambda - IntSupplier example








IntSupplier represents a supplier of int-valued results. This is the int-producing primitive specialization of Supplier.

Method

  1. IntSupplier getAsInt

Example

The following example shows how to use IntSupplier.

import java.util.function.IntSupplier;
/*w  w w .  java 2  s .co  m*/
public class Main {

  public static void main(String[] args) {
    IntSupplier i = ()-> Integer.MAX_VALUE;
    
    System.out.println(i.getAsInt());

  }
}

The code above generates the following result.





Example 2

The following code shows how to generate fibonnaci from IntSupplier.

import java.util.function.IntSupplier;
import java.util.stream.IntStream;
/*from w ww  .ja  v a2s .c  o m*/
public class Main {

  public static void main(String[] args) {
    IntSupplier fib = new IntSupplier() {
      private int previous = 0;
      private int current = 1;

      public int getAsInt() {
        int nextValue = this.previous + this.current;
        this.previous = this.current;
        this.current = nextValue;
        return this.previous;
      }
    };
    IntStream.generate(fib).limit(10).forEach(System.out::println);
  }

}

The code above generates the following result.