Sobes.tech
Middle

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 type T and returns a result of type T. It is a specialization of Function<T, T>.

    java.util.function.UnaryOperator<Integer> increment = x -> x + 1;
    int result = increment.apply(5); // result = 6
    
  • DoubleUnaryOperator: Takes an argument of type double and returns a result of type double.

    java.util.function.DoubleUnaryOperator square = x -> x * x;
    double result = square.applyAsDouble(2.5); // result = 6.25
    
  • IntUnaryOperator: Takes an argument of type int and returns a result of type int.

    java.util.function.IntUnaryOperator negate = x -> -x;
    int result = negate.applyAsInt(10); // result = -10
    
  • LongUnaryOperator: Takes an argument of type long and returns a result of type long.

    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.

What are UnaryOperator<T>, DoubleUnaryOperator… - sobes.tech