Arrow Operator in Java

The arrow operator (->) in Java is explained in this article along with some sample code to help you grasp the concept.

The arrow operator, which is used to create lambda expressions, was introduced along with the addition of the lambda expression functionality in Java 8. It divides the expression body from the arguments.

To make Java code more understandable and concise, lambda expression, which was introduced by Java 8, can be employed in place for anonymous classes.

An illustration of how to build an anonymous class using Java prior to Java 8 is shown below.

And here's how we may carry out the aforementioned task in Java 8 utilizing a lambda expression.

To better grasp how to use the lambda and arrow operators, let's start with some examples.

How to use Arrow Operator in Java?

In this illustration, the draw() method of both the Drawable interface was implemented using a lambda expression and the arrow operator. See the illustration below.

M.java

Output:

Arrow Operator in Java

We can utilize lambda expression in Java programming in a variety of ways because it's a great technique to write succinct code using a functional approach. Here are several instances where we can use it.

Array Operator in Java collection

In this illustration, we use a lambda expression to filter data from an ArrayList. To achieve the desired outcome, we used the filter() method and the stream API. You can see how much simpler lambda code is to write than non-lambda code. See the illustration below.

M1.java

Output:

Tutorial and example: 100500.0
Website: 25000.0

Array operator in Java thread

In order to implement the run() method of both the runnable interface, we used lambda expression in this instance. A lambda expression can be used with ease because Runnable has a single method interface. see the illustration below.

M3.java

Output:

 Thread is running...