Function Functional Interface
Approach
Function কী?
Function হলো Java-এর একটি Functional Interface, যা একটি ইনপুট নিয়ে অন্য একটি আউটপুটে রূপান্তর (transform) করে।
সহজ ভাষায়:
Function = Input → Output
উদাহরণ:
- String → Integer
- User → DTO
- Number → Square
Function Interface-এর গঠন
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
এখানে:
T= Input টাইপR= Output টাইপapply()= transformation logic
Function কেন দরকার?
যখন:
- ডাটা এক ফরম্যাট থেকে আরেক ফরম্যাটে নিতে হয়
- map / convert / calculate করতে হয়
- Stream-এর
map()ব্যবহার করতে হয়
সহজ Function উদাহরণ
সংখ্যা → তার বর্গ
Function<Integer, Integer> square = n -> n * n;
System.out.println(square.apply(5)); // 25
String Transformation উদাহরণ
Function<String, Integer> length =
s -> s.length();
System.out.println(length.apply("Java")); // 4
Stream-এর সাথে Function ব্যবহার
List<String> names = List.of("Rahim", "Karim", "Amin");
names.stream()
.map(name -> name.length())
.forEach(System.out::println);
এখানে map()-এর ভিতরের Lambda আসলে একটি Function
আলাদা Function লিখে ব্যবহার
Function<String, String> toUpper =
s -> s.toUpperCase();
names.stream()
.map(toUpper)
.forEach(System.out::println);
Object → Object Transformation (বাস্তব উদাহরণ)
User → UserDTO
class User {
String name;
int age;
}
class UserDTO {
String name;
}
Function<User, UserDTO> toDto = user -> {
UserDTO dto = new UserDTO();
dto.name = user.name;
return dto;
};
Function chaining (andThen, compose)
Function-এর দুটি শক্তিশালী default method আছে।
andThen() – আগে this, পরে next
Function<Integer, Integer> doubleIt = n -> n * 2;
Function<Integer, Integer> square = n -> n * n;
Function<Integer, Integer> result =
doubleIt.andThen(square);
System.out.println(result.apply(3)); // (3*2)^2 = 36
compose() – আগে next, পরে this
Function<Integer, Integer> result =
doubleIt.compose(square);
System.out.println(result.apply(3)); // (3^2)*2 = 18
identity() – নিজেকেই রিটার্ন করে
Function<String, String> identity =
Function.identity();
System.out.println(identity.apply("Java")); // Java
Primitive Function (পারফরম্যান্স ভালো)
- IntFunction
- ToIntFunction
- IntToDoubleFunction
উদাহরণ
ToIntFunction<String> length =
String::length;
Function বনাম Predicate বনাম Consumer
| Interface | ইনপুট | আউটপুট |
|---|---|---|
| Function | T | R |
| Predicate | T | boolean |
| Consumer | T | void |
| Supplier | none | T |