Java UnaryOperator

Introduction

In Java, the UnaryOperator interface is a functional interface that represents an operation on a single operand that produces a result of the same type. It is part of the java.util.function package and is commonly used for operations that transform or modify an object of a certain type.

Table of Contents

  1. What is UnaryOperator?
  2. Methods and Syntax
  3. Examples of UnaryOperator
  4. Real-World Use Case
  5. Conclusion

1. What is UnaryOperator?

UnaryOperator is a functional interface that takes an operand of type T and returns a result of the same type. It is useful for scenarios where a single value needs to be transformed or modified.

2. Methods and Syntax

The main method in the UnaryOperator interface is:

  • T apply(T t): Applies this operator to the given operand and returns a result.

Syntax

UnaryOperator<T> operator = (T t) -> {
    // operation on t
    return result;
};

3. Examples of UnaryOperator

Example 1: Incrementing a Number

import java.util.function.UnaryOperator;

public class IncrementExample {
    public static void main(String[] args) {
        // Define a UnaryOperator that increments a number by 1
        UnaryOperator<Integer> increment = (value) -> value + 1;

        int result = increment.apply(5);
        System.out.println("Incremented Value: " + result);
    }
}

Output:

Incremented Value: 6

Example 2: Converting String to Uppercase

import java.util.function.UnaryOperator;

public class UppercaseExample {
    public static void main(String[] args) {
        // Define a UnaryOperator that converts a string to uppercase
        UnaryOperator<String> toUpperCase = (str) -> str.toUpperCase();

        String result = toUpperCase.apply("hello");
        System.out.println("Uppercase: " + result);
    }
}

Output:

Uppercase: HELLO

4. Real-World Use Case: Removing Whitespace from a String

In applications, UnaryOperator can be used to remove leading and trailing whitespace from a string.

import java.util.function.UnaryOperator;

public class TrimWhitespaceExample {
    public static void main(String[] args) {
        // Define a UnaryOperator to trim whitespace from a string
        UnaryOperator<String> trimWhitespace = (str) -> str.trim();

        String result = trimWhitespace.apply("   Hello, World!   ");
        System.out.println("Trimmed String: '" + result + "'");
    }
}

Output:

Trimmed String: 'Hello, World!'

Conclusion

The UnaryOperator interface is a practical tool in Java for transforming or modifying objects of a certain type. It is particularly beneficial in scenarios requiring simple transformations or modifications. Using UnaryOperator can lead to cleaner and more efficient code, especially in functional programming contexts.

Comments