Welcome to our comprehensive guide on Java's UnaryOperator! This tutorial is designed to help both beginners and intermediate learners understand and utilize this powerful functional interface. Let's dive in!
UnaryOperator is a functional interface in Java 8 and later versions. It represents a single-argument operation (binary operation with one operand) that returns a result of the same type as the input. It's useful when you want to apply a function that only takes one argument and returns a value of the same type.
R unaryOperation(T t);Here, T is the type of the input, and R is the type of the result.
Let's create a simple example to illustrate how UnaryOperator works.
import java.util.function.UnaryOperator;
public class Main {
public static void main(String[] args) {
UnaryOperator<Integer> increment = i -> i + 1;
System.out.println(increment.apply(5)); // Output: 6
}
}In this example, we've defined a UnaryOperator called increment that increments an integer by 1.
What is the purpose of UnaryOperator in Java?
UnaryOperator can be used in combination with other functional interfaces like Predicate, Function, and BiFunction to create more complex operations.
import java.util.function.*;
public class Main {
public static void main(String[] args) {
UnaryOperator<Integer> increment = i -> i + 1;
Predicate<Integer> isEven = i -> i % 2 == 0;
int evenNumber = findEvenNumber(increment, isEven, 5);
System.out.println(evenNumber); // Output: 8
}
static int findEvenNumber(UnaryOperator<Integer> increment, Predicate<Integer> isEven, int start) {
int number = start;
while (!isEven.test(number)) {
number = increment.apply(number);
}
return number;
}
}In this example, we use UnaryOperator to increment a number, and Predicate to check if a number is even. The findEvenNumber method finds the smallest even number greater than a given start number.
That's it for our Java UnaryOperator tutorial! We hope this guide has been helpful in understanding this important functional interface in Java. Happy coding! 🚀