What are UnaryOperator<T>, DoubleUnaryOperator, IntUnaryOperator, and LongUnaryOperator functional interfaces used for?
sobes.tech AI
Answer from AI
These functional interfaces are used to represent unary operations that take one argument of a specific type and return a result of the same type.
-
UnaryOperator<T>: Takes an argument of typeTand returns a result of typeT. It is a specialization ofFunction<T, T>.java.util.function.UnaryOperator<Integer> increment = x -> x + 1; int result = increment.apply(5); // result = 6 -
DoubleUnaryOperator: Takes an argument of typedoubleand returns a result of typedouble.java.util.function.DoubleUnaryOperator square = x -> x * x; double result = square.applyAsDouble(2.5); // result = 6.25 -
IntUnaryOperator: Takes an argument of typeintand returns a result of typeint.java.util.function.IntUnaryOperator negate = x -> -x; int result = negate.applyAsInt(10); // result = -10 -
LongUnaryOperator: Takes an argument of typelongand returns a result of typelong.java.util.function.LongUnaryOperator powerOfTwo = x -> 1L << x; long result = powerOfTwo.applyAsLong(3); // result = 8
They are often used when working with streams (Stream API) or as parameters to methods that require passing transformation logic of one value to another of the same type. Specialized versions (Double, Int, Long) prevent autoboxing/unboxing when working with primitive types, which improves performance.