১️Function কী?
Function হলো Java-এর একটি Functional Interface, যা একটি ইনপুট নিয়ে অন্য একটি আউটপুটে রূপান্তর (transform) করে।
সহজ ভাষায়:
Function = Input → Output
উদাহরণ:
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
এখানে:
T = Input টাইপ
R = Output টাইপ
apply() = transformation logicযখন:
map() ব্যবহার করতে হয়Function<Integer, Integer> square = n -> n * n;
System.out.println(square.apply(5)); // 25
Function<String, Integer> length =
s -> s.length();
System.out.println(length.apply("Java")); // 4
List<String> names = List.of("Rahim", "Karim", "Amin");
names.stream()
.map(name -> name.length())
.forEach(System.out::println);
এখানে map()-এর ভিতরের Lambda আসলে একটি Function
Function<String, String> toUpper =
s -> s.toUpperCase();
names.stream()
.map(toUpper)
.forEach(System.out::println);
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-এর দুটি শক্তিশালী default method আছে।
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
Function<Integer, Integer> result =
doubleIt.compose(square);
System.out.println(result.apply(3)); // (3^2)*2 = 18
Function<String, String> identity =
Function.identity();
System.out.println(identity.apply("Java")); // Java
ToIntFunction<String> length =
String::length;
| Interface | ইনপুট | আউটপুট |
|---|---|---|
| Function | T | R |
| Predicate | T | boolean |
| Consumer | T | void |
| Supplier | none | T |