M Sach
M Sach

Reputation: 34424

Why lambda expression in java?

I understand with lambda expression(LE) we can save few lines of coding like object creation for functional interface. Also LE will be more readable. But i am sure that this is not the main reason this feature is provided for. I search it on google for Why Lambda expression in java and i found this interesting quote at this article

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. If the requirement is to process the elements in parallel, it would be done by the client code. With the introduction of Stream API in Java 8, functions can be passed to collection methods and now it is the responsibility of collection to process the elements either in a sequential or parallel manner. -

To me this looks like the advantage of streaming api not LE. Even if LE was not provided developer could have achieved the same with creation of anonymous Consumer class. The only advantage here i can see in favour of LE is developer does not have to remember object of which functional interface needs to be created. So it takes java towards functional programming where dev is saying apply this function and he does not care about object(let jvm handle this).

Is this the main advantage of LE or there is another one major than this ?

Update :-

I tried below simple program where i tried to measure the performance parallel processing with lambda expression. Found that it took 84 unit of time with parallel processing and only 4 unit for sequential. Is it because program is not big enough and also thread overhead may be playing its role here ? May be advantages can be visible in larger function ?

public class Java8Tester {

   final static String salutation = "Hello! ";

   public static void main(String args[]){
      List<String> stringList = new ArrayList<String>();


      for(int i=0;i <100;i++){
      stringList.add("Hello1");
      stringList.add("Hello2");
      }

     long startTime  = System.currentTimeMillis();
       System.out.println(startTime);
      stringList.parallelStream().forEach((string) -> {System.out.println("content is " + string);
      });
      long stopTime  = System.currentTimeMillis();
      System.out.println(stopTime);
      System.out.println("time taken in parallel processing" + (stopTime - startTime)); // took 84 units of time


       startTime  = System.currentTimeMillis();
       System.out.println(startTime);

     for(String str : stringList ) {
         System.out.println("content is " + str);
     }

       stopTime  = System.currentTimeMillis();
      System.out.println(stopTime);
      System.out.println("time taken in sequential processing" + (stopTime - startTime)); // // took 4 units of time
   }


}

Upvotes: 6

Views: 3370

Answers (3)

hi.nitish
hi.nitish

Reputation: 2974

Lambda Expression comes as a great plus feature in java 8. It allows faster development and is based on functional programming. There are different ways to use lambda expression in your code depending upon the compiler is able to identify data types, return types, overloaded function uniquely (smart compiling is also called Type inference). For the Lexical scoping, Link can be referred. Following are the ways you can use lambda expression:

a. if you want to define a method declared inside a functional interface, say, the functional interface is given as an argument/parameter to a method called from main

    @FunctionalInterface
    interface FInterface{
     int callMeLambda(String temp);
    }

   class ConcreteClass{

     void funcUsesAnonymousOrLambda(FInterface fi){
      System.out.println("===Executing method arg instantiated with Lambda==="));
     }

     public static void main(){
      // calls a method having FInterface as an argument.
      funcUsesAnonymousOrLambda(new FInterface() {

      int callMeLambda(String temp){ //define callMeLambda(){} here..
      return 0;
    }
    });

    /***********Can be replaced by Lambda below*********/
    funcUsesAnonymousOrLambda( (x) -> {
     return 0; //(1)
    }

    }

FInterface fi = (x) -> { return 0; };

funcUsesAnonymousOrLambda(fi);

Above is explains a particular usage of lambda expression, Let us take the locs with which we can see various other usages --

 funcUsesAnonymousOrLambda( (String x) {
     return 0;
     });

can be implemented using lambda expr in many ways a. without curly braces, if only one liner--

  funcUsesAnonymousOrLambda((String x) -> return 0);

b. Without return statement above (compiler is very smart to identify return automatically) funcUsesAnonymousOrLambda((String x) -> 0);

c. Without specifying String type of arg

funcUsesAnonymousOrLambda((x) -> 0);

d.
With curly braces and new local field initialised

funcUsesAnonymousOrLambda( (String x) ->
{ //curly braces as we need more statements

String newVarString = " world";
Sysout("___" + x +  newVarString);

});

NOTE: the above local field can be there but if some field from outer scope (local variable of outer method) is accessed inside, it allows getting that field but not modifying that field. ref Java 8 lambda within a lambda can't modify variable from outer lambda

Collections.sort(list, (o1, o2) -> {return o1.compareTo(o2);}

Lambda Expr is also useful while implementing Comparator interface(much like above example) while implementing compare method. Python is preferred sometimes over java when fast development is the requirement but lambda gives a new curve to java.

Upvotes: 0

Luke Melaia
Luke Melaia

Reputation: 1468

I don't think lambda expressions have one main purpose, rather lots of small added benefits, that together make a huge impact.

  • Lambdas remove a lot of boilerplate code.

  • They make code shorter and easier to read.

  • Reduced need for anonymous inner classes.

  • Allows more code reuse.

Any many more features.

One of my favourite advantages of lambdas is the ability to make default interfaces methods. Something I don't think I can live without now.

So lambdas don't have one specific reason for existing. They open the doors to a lot more functional programming, allow Java to evolve, and overall make coding even more fun.

Upvotes: 6

Tagir Valeev
Tagir Valeev

Reputation: 100199

In general you're right: Stream API could exist without lambda functions, using anonymous classes. Though it would look really ugly and work somewhat less efficiently. As for time measurement, your results are completely irrelevant. See this question for details.

Upvotes: 3

Related Questions