How to implement IntFunction with lambda expression in Java?


IntFunction interface is a functional interface in Java 8 and defined in java.util.function package. This interface accepts an int-valued parameter as input and returns a value of type R. IntFunction interface can be used as an assignment target for a lambda expression or method reference and holds only one abstract method, apply().

Syntax

@FunctionalInterface
public interface IntFunction<R> {
   R apply(int value);
}

Example

import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;

public class IntFunctionTest {
   public static void main(String[] args) {
      IntFunction<String> getMonthName = monthNo -> {  // lambda expression
         Map<Integer, String> months = new HashMap<>();
         months.put(1, "January");
         months.put(2, "February");
         months.put(3, "March");
         months.put(4, "April");
         months.put(5, "May");
         months.put(6, "June");
         months.put(7, "July");
         months.put(8, "August");
         months.put(9, "September");
         months.put(10, "October");
         months.put(11, "November");
         months.put(12, "December");
         if(months.get(monthNo)!= null) {
            return months.get(monthNo);
         } else {
            return "The number must between 1 to 12";
         }
      };
      int input = 1;
      String month = getMonthName.apply(input);
      System.out.println("Month number "+ input +" is: "+ month);
      input = 10;
      System.out.println("Month number "+ input +" is: "+ getMonthName.apply(input));
      input = 15;
      System.out.println("Month number "+ input +" is: "+ getMonthName.apply(input));
   }
}

Output

Month number 1 is: January
Month number 10 is: October
Month number 15 is: The number must between 1 to 12

Updated on: 13-Jul-2020

327 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements