Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement IntFunction<R> 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
Advertisements