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 Function<T, R> interface with lambda expression in Java?\\n
Function<T, R> interface is a functional interface from java.util.function package. This interface expects one argument as input and produces a result. Function<T, R> interface can be used as an assignment target for a lambda expression or method reference. It contains one abstract method: apply(), two default methods: andThen() and compose() and one static method: identity().
Syntax
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Example
import java.util.function.Function;
public class FunctionTest {
public static void main(String[] args) {
Function<Integer, Integer> f1 = i -> i*4; // lambda
System.out.println(f1.apply(3));
Function<Integer, Integer> f2 = i -> i+4; // lambda
System.out.println(f2.apply(3));
Function<String, Integer> f3 = s -> s.length(); // lambda
System.out.println(f3.apply("Adithya"));
System.out.println(f2.compose(f1).apply(3));
System.out.println(f2.andThen(f1).apply(3));
System.out.println(Function.identity().apply(10));
System.out.println(Function.identity().apply("Adithya"));
}
}
Output
12 7 7 16 28 10 Adithya
Advertisements