How do I use the UnaryOperator functional interface in Java?

The UnaryOperator functional interface in Java is a specialized form of the Function functional interface. It is used when both the input and output of a function are of the same type. This interface plays a role when we want to perform an operation on a single operand and return a result of the same type.

Key Characteristics:

  • Package: It’s part of the java.util.function package.
  • Functional method: The single abstract method in this interface is apply(T t).

Example Syntax:

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
}

Usage Example:

1. Basic Example

A simple example is doubling an integer:

package org.kodejava.util.function;

import java.util.function.UnaryOperator;

public class UnaryOperatorExample {
    public static void main(String[] args) {
        // UnaryOperator to double a number
        UnaryOperator<Integer> doubleNumber = x -> x * 2;

        // Apply the operator
        Integer result = doubleNumber.apply(5);
        System.out.println(result);
        // Output: 10
    }
}

2. Using UnaryOperator with Lists

We can use UnaryOperator to modify elements in a List using replaceAll:

package org.kodejava.util.function;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

public class ListOperatorExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Rosa");

        // UnaryOperator to convert strings to uppercase
        UnaryOperator<String> toUpperCase = String::toUpperCase;

        // Replace all elements in the list using the operator
        names.replaceAll(toUpperCase);

        // Print modified list
        System.out.println(names);
        // Output: [ALICE, BOB, ROSA]
    }
}

3. Using the identity() Method

The identity() method returns a UnaryOperator that simply returns the input as it is:

package org.kodejava.util.function;

import java.util.function.UnaryOperator;

public class UnaryOperatorIdentityExample {
    public static void main(String[] args) {
        // UnaryOperator using identity
        UnaryOperator<String> identityOperator = UnaryOperator.identity();

        // Apply the operator
        String result = identityOperator.apply("Hello World");
        System.out.println(result);
        // Output: Hello World
    }
}

4. Composing with Other Methods

We can chain UnaryOperator methods using the default methods andThen and compose:

package org.kodejava.util.function;

import java.util.function.Function;
import java.util.function.UnaryOperator;

public class ComposeExample {
    public static void main(String[] args) {
        UnaryOperator<Integer> square = x -> x * x; // Square of a number
        UnaryOperator<Integer> increment = x -> x + 1; // Increment by 1

        // Compose the operators
        Function<Integer, Integer> squareThenIncrement = square.andThen(increment);

        // Apply the composed operator
        Integer result = squareThenIncrement.apply(4);
        System.out.println(result);
        // Output: 17 (4 * 4 = 16, then 16 + 1 = 17)
    }
}

When to Use UnaryOperator

Use UnaryOperator when:
1. We have a function that takes one argument and returns a value of the same type.
2. The input and output types are guaranteed to be the same.
3. We want to manipulate lists or streams of elements of the same type.

By following these examples and understanding its purpose, the UnaryOperator becomes a handy tool while working with functional-style programming in Java.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.