 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use UnaryOperator<T> interface in lambda expression in Java?
UnaryOperator<T> is a functional interface that extends the Function interface. It represents an operation that accepts a parameter and returns a result of the same type as its input parameter. The apply() method from Function interface and default methods: andThen() and compose() are inherited from the UnaryOperator interface. A lambda expression and method reference can use UnaryOperator objects as their target.
Syntax
@FunctionalInterface public interface UnaryOperator<T> extends Function<T, T>
Example-1
import java.util.function.UnaryOperator; public class UnaryOperatorTest1 {    public static void main(String[] args) {       UnaryOperator<Integer> operator = t -> t * 2;   // lambda expression       System.out.println(operator.apply(5));       System.out.println(operator.apply(7));       System.out.println(operator.apply(12));    } } Output
10 14 24
Example-2
import java.util.function.UnaryOperator; public class UnaryOperatorTest2 {    public static void main(String[] args) {       UnaryOperator<Integer> operator1 = t -> t + 5;       UnaryOperator<Integer> operator2 = t -> t * 5;       // Using andThen() method       int a = operator1.andThen(operator2).apply(5);       System.out.println(a);       // Using compose() method       int b = operator1.compose(operator2).apply(5);       System.out.println(b);    } } Output
50 30
Advertisements
 