Home  >  Java 8

Java IntSupplier Example

By Arvind Rai, May 04, 2020
This page will walk through IntSupplier example. The IntSupplier is the functional interface introduced in Java 8 under the java.util.function package. The IntSupplier is the int-producing primitive specialization of Supplier functional interface. The functional method of IntSupplier is getAsInt() which returns integer result. Find the IntSupplier structure from Java doc.
@FunctionalInterface
public interface IntSupplier {
    int getAsInt();
} 
The IntSupplier can be instantiated using lambda expression and method reference. Here we will provide using IntSupplier in our applications in detail.

Using Lambda Expression

Find the code to instantiate IntSupplier using lambda expression.
IntSupplierWithLE.java
package com.concretepage;
import java.time.LocalDate;
import java.util.function.IntSupplier;
public class IntSupplierWithLE {
  public static void main(String[] args) {
      IntSupplier yearIs = () -> LocalDate.now().getYear();
      System.out.println(yearIs.getAsInt());

      IntSupplier msgIs = () ->  "Hello World!".length();
      System.out.println(msgIs.getAsInt());      
      
      IntSupplier is = () -> {
    	int num1 = 10;
    	int num2 = 20;
    	return num1 * num2;
      };
      System.out.println(is.getAsInt());  
  }
} 
Output
2020
12
200 

Using Method Reference

Find the code to instantiate IntSupplier using method reference.
IntSupplierWithMR.java
package com.concretepage;
import java.time.LocalDateTime;
import java.util.function.IntSupplier;
public class IntSupplierWithMR {
  public static void main(String[] args) {
	IntSupplier monthIs = LocalDateTime.now()::getMonthValue;
	System.out.println(monthIs.getAsInt());
	
	IntSupplier dbConIs = AppUtil::noOfDBConnections;
	System.out.println(dbConIs.getAsInt());
  }
}

class AppUtil {
  public static int noOfDBConnections() {
	return 20;
  }
} 
Output
5
20 

Passing as Method Parameter

Here we will pass IntSupplier as method parameter.
WithMethodParameter.java
package com.concretepage;
import java.util.Random;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
public class WithMethodParameter {
  public static void main(String[] args) {
	String id = createTempId(() -> new Random().nextInt(100));
	System.out.println(id);

	System.out.println("--- With IntStream.generate() ---");
	IntStream intStream = IntStream.generate(() -> new Random().nextInt(10)).limit(5);
	intStream.forEach(v -> System.out.println(v));
  }

  static String createTempId(IntSupplier is) {
	return "temp-id-" + is.getAsInt();
  }
} 
Output
temp-id-51
--- With IntStream.generate() ---
8
7
7
6
4 

Reference

Java doc: IntSupplier
POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us