java 8 core features – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 15:01:03 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg java 8 core features – Programmerbay https://programmerbay.com 32 32 Predefined Functional Interface in Java 8 https://programmerbay.com/predefined-functional-interface-in-java-8/ https://programmerbay.com/predefined-functional-interface-in-java-8/#respond Sun, 14 Jun 2020 15:48:47 +0000 https://programmerbay.com/?p=6431 Java provides a bunch of predefined functional interfaces that come under java.util.function package. Each and every predefined functional interface has its own characteristics. Some of the major ones are : predicate, consumer, supplier and function.

Predicate

– It accepts a single input and always returns a boolean value as an output
– In other words, it is used for conditional checks
– It supports a single abstract method named test()
– it always return a boolean type

For example:

import java.util.function.Predicate;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Predicate<Integer> ageTester = (x) -> x>18;
        if(ageTester.test(15))
        {
            System.out.println("You can vote");
        }
        else
        {

            System.out.println("You are too young");
        }
    }
}

Output:

You are too young

 

Function

– It is used for performing logic on given input.
– It takes two arguments first is to represent input and second is for output.
– It supports a single abstract method named apply()
– Its return type can be varied

For example:

import java.util.function.Function;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Function<Integer,Integer> calculator = (x) -> 4*4;
        System.out.println("Square : "+calculator.apply(4));
    }
}

Output:

Square: 16

Function chaining: Combining two or more functions to form more complex function is known as function chaining.

 

Consumer

– It accepts a single input argument but returns nothing
– It supports a single abstract method named accept()
– It doesn’t have any return type

For example:

import java.util.function.Consumer;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Consumer<Integer> display = (x) -> System.out.println("I am displaying "+ x);
       display.accept(10);
    }
}

Output:

I am displaying 10

 

Supplier

– It accepts no argument but returns a value
– It must return something
– It supports a single abstract method named get()

For example:

import java.util.Date;
import java.util.function.Supplier;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Supplier<Date> date = () -> new Date();
        System.out.println("Date : "+date.get());

    }
}

Output:

Date : Mon Jun 15 16:31:22 IST 2020

Other functional Interfaces

There are more predefined functional interfaces:-

  • Interfaces that accepts two arguments:
    -BiFunction
    -BiPredicate
    -BiConsumer
  •  Interfaces that accept a specific datatype:
    DoubleSupplier
    DoubleConsumer
    IntPredicate
    IntSupplier
    and more
  • Other intefaces are BinaryOperator, UnaryOperator

]]>
https://programmerbay.com/predefined-functional-interface-in-java-8/feed/ 0
What is Functional Interface in Java 8 https://programmerbay.com/functional-interface-in-java-8/ https://programmerbay.com/functional-interface-in-java-8/#respond Sun, 14 Jun 2020 15:48:03 +0000 https://programmerbay.com/?p=6430 Programming languages such as Python, Scala that support functional programming , require few lines to complete a particular functionality, therefore, they are concise, on the flip side, Java can do the same thing but requires more lines of code.

In other words,one of the drawback of Java was that even a single functionality one require to create a method and that method is intended to be invoked by a class object. That certainly increases the length of the code.

To compete with other languages, Java developers decided to have functional programming as a new feature in Java.

To achieve this, Functional interface, Lambda Expressions (other alternatives such as Method reference and constructor references ) and many other features were introduced.

Functional Interface

A functional interface can be defined as an interface that consists exactly a single abstract method. However, it can have any number of static or default methods.

In order to use or implement Lambda expression, it is compulsory to use functional interface. A functional Interface is responsible for invoking Lambda expressions.

We cannot write Lambda expression without providing functional interface.

Functional Interface Annotation

@FunctionalInterface annotation is used to explicitly tell the compiler that a particular interface is intended to be a functional interface. A compiler triggers an error when a particular interface doesn’t satisfy the criteria of having a functional interface.

Runnable,Collable, Comparable are some examples of Functional interface.

A functional interface uses lambda expressions, method references or constructor references as one of the ways of its instance creation.

@FunctionalInterface
interface MyFunctionInterface{
        boolean compareMe(int a,int b);
        }



public class FunctionInterfaceExample {
    public static void main(String[] args) {
        int num=9,num1=8;
        MyFunctionInterface i = (a,b) ->  a>b;
       if(i.compareMe(num,num1))
           System.out.println(num+" is greater than "+num1);
       else
        System.out.println(num+" is smaller than "+num1);
    }
}

Output:

ouput

]]>
https://programmerbay.com/functional-interface-in-java-8/feed/ 0
Lambda expression in Java 8 https://programmerbay.com/lambda-expression-in-java-8/ https://programmerbay.com/lambda-expression-in-java-8/#respond Sun, 14 Jun 2020 15:47:03 +0000 https://programmerbay.com/?p=6429 Lambda expression is one of the core feature introduced in Java 8 as it provides a way to achieve functional programming in an object oriented programming language. It is anonymous function without having modifiers and return type. In other words, it simply provides a definition to a single abstract method defined within an interface called as Functional interface.

Point to remember:

– It provides a way to achieve functional programming in Java

-A Lambda expression is anonymous function having no modifiers and return type.

– It uses functional interfaces as its base to implement functional programming in Java. Without functional interface it cannot be implemented.

-It uses arrow operator or lambda operator to tell the compiler it is a Lambda expression

Syntax:

lambda expressions

These are following features of a lambda expression:

another lambda
No return type: Unlike function, in lambda expression, we don’t provide the return type. We simply write () -> {}

No Modifiers: Another important aspect of Lambda expression is, no modifier is required to mention.

The above two aspects indirectly depends on abstract method of a functional interface. Lambda Expression indirectly references to that type.

Optional Argument type : It is not mandatory to provide datatype to the parameter, but if one does then parenthesis would be mandatory

Optional Parenthesis : if there is a single argument then putting parenthesis would be optional
Optional curly braces and return type : if there is a single statement in the expression body then there is no need to put curly braces and return statement(if have).

 

 

Before Lambda Expression:

create a function:

void cube(int x) {
System.out.println("cube :"+ x*x*x);

}

create an object to call that function:

Test obj = new Test();

Invoke it

obj.cube(3);

 

After Lambda Expression:

Import Function (A predefined functional interface)

import java.util.function.Function;

Create a Lambda expression:

Function<Integer,Integer> cube = x -> x*x*x;

call its apply abstract method

System.out.println("This is the cube of "+ x + ":"+ cube.apply(x));

]]>
https://programmerbay.com/lambda-expression-in-java-8/feed/ 0