Saturday, March 5, 2016

Java 8 Lambda Expressions-Continued

As we see in the previous series Lambda expression,we used an Functional interface and created a Lambda expression by removing the anonymous inner class code.

Here we will see that we can do the same job without using our custom functional interface.But here we will take the help of some of the inbuilt functional  interfaces which is provided in java8 in package java.util.function.



@FunctionalInterface
public interface Predicate <T>{
  boolean test(T t);
.
.
.
.
}

Here parameter T is the type of the input to the predicate
Here the Functional Interface Predicate given in package  java.util.function represents a boolean-valued function(predicate) of a single argument.It has one abstract method test(Object obj).

Let's see the example below


package com.brainatjava;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Test {
    static List wordList = Arrays.asList(new String[]{"a","b","Lambda","d"});
    public static void findString(List list, Predicate predicate) {
            for (String p : list) {
                if (predicate.test(p)) {
                   System.out.println("we found Lambda anonymously.");
                }
            }
        }
    public static void main(String[] args) {
        findString(wordList,x->x.equalsIgnoreCase("Lambda"));
    }
}


Now let's see some other built in functional interfaces and it's use case.

@FunctionalInterface
public interface Function {
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t); ....
....
//along with some other methods

}

It has an abstract method namely apply having argument T and return type R.
Suppose we have a requirement to take some strings and convert those into doubles.
So we will take the help of the apply() method of the above  functional interface.
So we wrote a method namely changeFormat like below.

public static List changeFormat(Function function, List source) {
        List sink = new ArrayList<>();
        for (T item : source) {
        R value = function.apply(item);
        sink.add(value);
        }
        return sink;
        }


package com.brainatjava;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

public class Test {     public static void main(String[] args) {
        List digits = Arrays.asList("1","2","9","7","5");         List numbers = changeFormat(n->new Double(n), digits);
    }

I request you to visit the official documentation from oracle to get  the knowledge of all available functional interfaces in java.util.fuction package those provide target types for lambda expressions and method references.

No comments:

Post a Comment