Middle
What are functional interfaces like Function<T, R>, DoubleFunction<R>, IntFunction<R>, and LongFunction<R> used for in Java?
sobes.tech AI
Answer from AI
These interfaces are used to represent operations that accept one argument and return a result.
-
Function<T, R>: Represents a function that accepts an argument of typeTand returns a result of typeR.// Example of using Function<String, Integer> Function<String, Integer> stringLength = s -> s.length(); int length = stringLength.apply("Hello"); // Result: 5 -
DoubleFunction<R>: Represents a function that accepts an argument of typedoubleand returns a result of typeR.// Example of using DoubleFunction<String> DoubleFunction<String> numberToString = d -> "Number: " + d; String text = numberToString.apply(3.14); // Result: "Number: 3.14" -
IntFunction<R>: Represents a function that accepts an argument of typeintand returns a result of typeR.// Example of using IntFunction<List<Integer>> IntFunction<List<Integer>> createList = size -> { List<Integer> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(i); } return list; }; List<Integer> numbers = createList.apply(5); // Result: [0, 1, 2, 3, 4] -
LongFunction<R>: Represents a function that accepts an argument of typelongand returns a result of typeR.// Example of using LongFunction<Date> LongFunction<Date> timestampToDate = timestamp -> new Date(timestamp); Date date = timestampToDate.apply(System.currentTimeMillis()); // Result: current date
These specialized interfaces (DoubleFunction, IntFunction, LongFunction) are used to avoid autoboxing when working with primitive types, which can improve performance.