Java 8 Examples

Java 8 UnaryOperator Example

Posted On
Posted By admin

In this blog post, I will be explaining how the Java 8 functional interface UnaryOperator works. To know more about functional interfaces, you can refer this blog post.

The UnaryOperator interface extends the Function interface. It inherits the apply method in the Function interface. The lambda expression passed to the UnaryOperator is used to provide an implementation for the apply method in the Function interface.

 

UnaryOperator example with Integer data type.

Consider the following code snippet:

public class UnaryOperatorDemo {

public static void main(String[] args) {

UnaryOperator<Integer> increaseBy5 = num -> num+5;
System.out.println("Output with input 7 is "+increaseBy5.apply(7));
}

}

Here, we have implemented the UnaryOperator.apply method using a lambda expression.  This method simply increases the value of the input number by 5 and returns it. So when you execute this code, it will print the following output:

Output with input 7 is 12

UnaryOperator example with Integer array as data type

Consider the following code snippet:

public class UnaryOperatorDemo {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11);

UnaryOperator<List<Integer>> increaseBy5 = input -> {
List<Integer> output = new ArrayList<Integer>();
input.forEach(num -> output.add(num+5));
return output;
};
List<Integer> output = increaseBy5.apply(list);
output.forEach(num -> System.out.println(num));

}

}

Again, the UnaryOperator accepts an Integer List.  It increments each element in the list by 5 and returns another list with these values. Within the lambda expression, it uses the forEach method to iterate on the input list, obtain each element, increment it by 5 and add it to the output list. So when you execute this code, it will print the following output:

10
8
16
20
14
7
10
16

 

 

You can get the source code for this example along with other code for other Java 8 examples at the Github repository here.

If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my new course Learn Java 8 New Features

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment