- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 ToIntFunction using lambda and method reference in Java?
ToIntFunction<T> is the built-in functional interface defined in java.util.function package. This functional interface expects an argument as input and produces an int-valued result. It can be used as an assignment target for a lambda expression or method reference. The ToIntFunction interface holds only one method, applyAsInt(). This method performs an operation on the given argument and returns the int-valued result.
Syntax
@FunctionalInterface public interface ToIntFunction { int applyAsInt(T value); }
In the below example, we can implement ToIntFunction<T> by using lambda expression and method reference.
Example
import java.util.function.ToIntFunction; import java.time.LocalDate; public class ToIntFunctionInterfaceTest { public static void main(String[] args) { ToIntFunction<Integer> lambdaObj = value -> value * 25; // using lambda expression System.out.println("The result is: " + lambdaObj.applyAsInt(10)); ToIntFunction<String> lenFn = String::length; // using method reference System.out.println("The length of a String is: " + lenFn.applyAsInt("tutorialspoint")); } }
Output
The result is: 250 The length of a String is: 14
Advertisements