hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Refresher Blog for Lambdas



How convenient would it be if you could write code or function and call it without object or without class reference?


Yes, Lambda expressions just do that.


Lambdas, Method references help to implement "Functional programming" in java.


Wherever a function is required to be passed, you can pass a Lambda or Method reference. ( Like we pass a variable or object reference, we can also pass reference of a Function. )


They are like regular function, but without a name.

This is a simple lambda.


     () -> {
	          for (int i = 1; i<11; i++)
		        System.out.println(i);
           };

Is it really that simple in Java?

Nope.. Functions have to be declared in a Functional interface and for this reference only you can pass a lambda. ex:

For the above lambda, there has to be a print() function declared in a Functional interface like this.


    @FunctionalInterface
    interface PrintNos {
	    void print();
    }

ok. Lets assign the lambda to the function above.


    PrintNos p = () -> {
	                     for (int i = 1; i < 11; I++)
	                        System.out.println(i);
                       };

How will we execute this lambda?


    p.print();

Why do we need functional programming ?

Lets understand with an example..

Assume you need to sort your Person class.


To sort custom objects, we can use Collections.sort(), but we need to say how we want to sort by providing our code..

<Person> void java.util.Collections.sort(List<Person> list, Comparator<? super Person> c)

Comparator is an interface which has compare method which needs to be implemented by us..

int compare(T o1, T o2);


Without Lambda, how will you pass in your code ?

when u need to pass a reference to an interface, you will provide the Object which implements that interface( ie, methods in them ) ; As there is only one method which needs to be implemented, you can declare & create object in place, providing its implementation on spot ( Anonymous classes )

     Collections.sort(personList, new Comparator<Person>() {
                @Override
                public int compare(Person p1, Person p2) {
                    return p1.getName().compareTo(p2.getName());
                }
            });

Your code is just one line.. Why cant we do it short and sweet with Lambda ?

     Collections.sort(persons, (p1, p2)-> 
                                p1.getName().compareTo(p2.getName())); 
                         

Wherever you see a functional interface as parameter, u can pass in a Lambda which wud give( or implement) the code for the abstract method in it..


Common Utility Functions :

Almost all projects may have common functions , which needs different implementations depending upon business requirement.. Instead of each developer creating separate functional interface and writing lambdas or method references , Java Guys have predefined them.. you can use them , so there will be uniformity in code and it will be easy to understand..


Lets start from Function, functional interface..


@FunctionalInterface
public interface Function<T, R> {
     R apply(T t);    
     
     default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
          Objects.requireNonNull(before); return (V v) -> 
          apply(before.apply(v)); 
        }
        
     default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) { 
          Objects.requireNonNull(after); 
          return (T t) -> after.apply(apply(t));
         }
         
     static <T> Function<T, T> identity() {
          return t -> t;
     }
}

This is a utility function which takes one argument and produces the result..


Lets get our hand in Lambda for apply function above..


     Function<Integer, String> ff = x -> { 
                              for ( int i =0; i < x; i++) 
    		                        System.out.println(" You are so Good " ); 
    	                          return "Bye";  
    	                          };
    	 ff.apply( 6);
              

compose, andThen are default methods.. so these are available for all Functions..

compose :

compose will accept a similar function to that of the one u r calling, and apply that before it executes the first one..

andThen : will apply the function u r calling, and then execute apply on the passed function..


New Functional Interfaces introduced in Java 8 :

Some preexisting interfaces were converted into functional interfaces in Java 8.

They are Runnable, Callable, Comparable, ActionListener interfaces. (Runnable , Comparable - java.lang package, Callable - java.util.concurrent, ActionListener - java.awt.event )

As we are aware of them, lets dive into newbies..

There are 43 new interfaces introduced in java.util.function package.

We'll group these into below categories..

1.Function 2.Predicate 3.Consumer 4.Supplier


Will discuss these in next blog..

Thank you for reading..




























31 views0 comments

Recent Posts

See All