Why should i use lambda expressions




















We care for our world. Learn about our ESG initiatives. Learn more. Thinking about becoming a Nagarrian? Check our open positions. Welcome to digital product engineering. Thanks for your interest. How can we help? Investor Relations. IR Home stock and financial information financial reports and publications corporate governance announcements corporate citizenship financial calendar events Merger Nagarro Holding GmbH.

Article 19 Dec 3 min read. Jayant Sahu. Why Lambdas in Java There are various reasons for addition of lambda expression in Java platform but the most beneficial of them is that we can easily distribute processing of collection over multiple threads. Also, parallel processing effectively utilizes multicore CPUs used nowadays.

Benefits of Lambda Expression 1. Fewer Lines of Code One of the benefits of using lambda expression is the reduced amount of code. We know that in Java lambda can be used only with functional interfaces. In the above example, Runnable is a functional interface, so we can easily apply lambda expression here In this case, we are not passing any parameter in lambda expression because the run method of the functional interface Runnable takes no argument.

In case of multiple statements, we should use curly braces as done in the above example. Sequential and Parallel Execution Support by passing behavior in methods Prior to Java 8, processing the elements of any collection could be done by obtaining an iterator from the collection and then iterating over the elements and then processing each element.

Lambda Expression and Objects In Java, any lambda expression is an object as is an instance of a functional interface. Where you can use Lambda expressions Lambda expressions can be used anywhere in Java 8 where we have a target type. In Java, we have target type in the following contexts Variable declarations and assignments Return statements Method or constructor arguments What do you think about this new feature in Java 8? Spread the word. Or check these related articles. Article 1 Jul When we motivate why functional programming is so powerful in Java 8, the Stream API should be emphasized.

A stream in Java 8 is a sequence of elements supporting sequential and parallel aggregate operations. By using streams, we can simply pass a block of code to the stream and apply the function to each element in the stream. Why do we need Lambda in Java? Sorting Before Java 8 The following example shows how to use a comparator to sort an array of self-defined objects. This is the dog class that need to be sorted. Arrays ; import java. Still, I don't understand why it's such an innovation.

It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method? Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL. The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:.

Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects. Expression trees are a very powerful new feature of C 3. Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.

I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created. This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this:. This code will search the list for an entry that matches the word "hello".

The other way to do this is to actually pass a delegate to the Find method, like this:. Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System. Expressions , which contains classes to create expression trees based on lambda expressions.

Expression trees are made up of objects that represent logic. Consider the following simple example:. This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own.

I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator.

You could also use it for Bayesian systems, or for genetic programming AI. A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions addition, subtrations, etc to operate on available data.

In pre-. Net 3. Net code on the fly. One of the arguments of the following invocation of the method printPersons is an anonymous class that filters members that are eligible for Selective Service in the United States: those who are male and between the ages of 18 and This approach reduces the amount of code required because you don't have to create a new class for each search that you want to perform.

However, the syntax of anonymous classes is bulky considering that the CheckPerson interface contains only one method.

In this case, you can use a lambda expression instead of an anonymous class, as described in the next section. The CheckPerson interface is a functional interface. A functional interface is any interface that contains only one abstract method. A functional interface may contain one or more default methods or static methods. Because a functional interface contains only one abstract method, you can omit the name of that method when you implement it. To do this, instead of using an anonymous class expression, you use a lambda expression , which is highlighted in the following method invocation:.

See Syntax of Lambda Expressions for information about how to define lambda expressions. You can use a standard functional interface in place of the interface CheckPerson , which reduces even further the amount of code required. This is a very simple interface. It's a functional interface because it contains only one abstract method.

This method takes one parameter and returns a boolean value. The method is so simple that it might not be worth it to define one in your application. Consequently, the JDK defines several standard functional interfaces, which you can find in the package java. This interface contains the method boolean test T t :. For more information about generics, see the Generics Updated lesson.

This interface contains only one type parameter, T. When you declare or instantiate a generic type with actual type arguments, you have a parameterized type. This parameterized type contains a method that has the same return type and parameters as CheckPerson. As a result, the following method invocation is the same as when you invoked printPersons in Approach 3: Specify Search Criteria Code in a Local Class to obtain members who are eligible for Selective Service:.

This is not the only possible place in this method to use a lambda expression. The following approach suggests other ways to use lambda expressions. Reconsider the method printPersonsWithPredicate to see where else you could use lambda expressions:.

This method checks each Person instance contained in the List parameter roster whether it satisfies the criteria specified in the Predicate parameter tester. If the Person instance does satisfy the criteria specified by tester , the method printPerson is invoked on the Person instance. Instead of invoking the method printPerson , you can specify a different action to perform on those Person instances that satisfy the criteria specified by tester.

You can specify this action with a lambda expression. Suppose you want a lambda expression similar to printPerson , one that takes one argument an object of type Person and returns void. Remember, to use a lambda expression, you need to implement a functional interface. In this case, you need a functional interface that contains an abstract method that can take one argument of type Person and returns void. The following method replaces the invocation p.

As a result, the following method invocation is the same as when you invoked printPersons in Approach 3: Specify Search Criteria Code in a Local Class to obtain members who are eligible for Selective Service. The lambda expression used to print members is highlighted:. What if you want to do more with your members' profiles than printing them out.

Suppose that you want to validate the members' profiles or retrieve their contact information? In this case, you need a functional interface that contains an abstract method that returns a value. The following method retrieves the data specified by the parameter mapper , and then performs an action on it specified by the parameter block :.

The following method retrieves the email address from each member contained in roster who is eligible for Selective Service and then prints it:. Reconsider the method processPersonsWithFunction. The following is a generic version of it that accepts, as a parameter, a collection that contains elements of any data type:. To print the e-mail address of members who are eligible for Selective Service, invoke the processElements method as follows:.



0コメント

  • 1000 / 1000