java 8 features – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 15:11:29 +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 features – Programmerbay https://programmerbay.com 32 32 Difference between Anonymous Inner Class and Lambda Expression in Java 8 https://programmerbay.com/difference-between-anonymous-inner-class-and-lambda-expression-in-java-8/ https://programmerbay.com/difference-between-anonymous-inner-class-and-lambda-expression-in-java-8/#respond Fri, 14 Aug 2020 15:49:25 +0000 https://programmerbay.com/?p=6432 An anonymous class is a class without a name, whose initialisation and instantiation are made at the same time. Whereas, Lambda expression is a method without a name, used to provide method behaviour or body of the method of functional interface.

Difference between anonymous inner class and Lambda Expression in Tabular Form

BasisAnonymous inner classLambda expression
DefinitionA class without having name termed as anonymous inner classIt is an anonymous function that provides a way to implement functional programming
Abstract MethodsIt can be used with interfaces having any number of abstract methodsIt can be used only with functional interface( having exactly one abstract method )
Instance CreationBeing a class, it can have its own instancesit can't be instantiated
MemoryDuring compilation, a separate .class file is generated that occupies more memory than Lambda expressionNo new file is generated
AdvantageTo avoid unnecessary creation of sub classesTo implement functional programming
this keywordthis keyword always refer to the instance of the anonymous class itself, not enclosing classthis keyword always refer to instance of enclosing class
UsageIt can be used with concrete classes, abstract classes.It cannot be used with concrete classes, abstract classes.

Anonymous inner class [Click here : to read in more depth]

A class without having any name is called anonymous inner class. It permits declaring and defining an object attribute and behaviour at the same time.

It concise the code and helps in avoiding the creation of sub classes.

It avoids the creation of subclass just for sake of overriding a method. It can be used with concrete class, abstract class, and interface.

Syntax:

className obj = new className{ 
//body 
}

for example:

interface  testInterface {
     void display();
     void extra();
}

public class AnonymousInnerClass {
    public static void main(String[] args) {
testInterface test = new testInterface() {
    @Override
    public void display() {
        System.out.println("My anonymous class implement testInterface");
    }

    @Override
    public void extra() {
        System.out.println("Another abstract method !! ");
    }
};

test.display();
test.extra();
    }
}

Output:

My anonymous class implement testInterface
Another abstract method !!

Lambda Expression

A lambda expression is an anonymous function that uses functional interface to implement functional programming in Java.

It works in companion with functional interface. A lambda expression can be defined as an anonymous function that represents instance of functional interface.

On the other hand, a functional interface is an interface that consists exactly one abstract method that later, referenced with lambda expression.

@FunctionalInterface annotation is used to tell the compiler that this interface is intended to be functional interface, if any criteria is violated the compiler would trigger compile time error. It is not mandatory to put the annotation, indeed, it is a good practise though.

It concise and reduces the complexity of the code.

For example

interface  testInterface {
     void display();
}

public class AnonymousInnerClass {
    public static void main(String[] args) {
testInterface test = () -> System.out.println("My Lambda Expression uses Function interface");
test.display();

    }
}

Output:

My Lambda Expression uses Function interface

Key Differences:

1) Lambda expression can be used where a class implements a functional interface to reduce the complexity of the code
2) Lambda expression cannot be used at all places where anonymous inner class, on the flip side, anonymous inner class can be used wherever Lambda expression is used
3) Inner anonymous class is more powerful as we can use as many methods as we want, whereas Lambda expression can only be used where an interface having only single abstract method

 

]]>
https://programmerbay.com/difference-between-anonymous-inner-class-and-lambda-expression-in-java-8/feed/ 0
What is Java Stream ? Explain with Examples https://programmerbay.com/stream-in-java-8-with-example/ https://programmerbay.com/stream-in-java-8-with-example/#respond Wed, 17 Jun 2020 17:26:41 +0000 https://programmerbay.com/?p=6437 What is a Stream in Java 8?

Another Java 8 important feature, it can be defined as a pipeline through which a collection of objects and primitive data can be streamed through and a set of operations are performed over each object.

streams

In other words, It is used to process a collection of objects. It streams over a sequence of objects from a source ( collection of objects or primitive types ), perform intermediate operations on each and every element of that source and provide the final outcome.
A stream can be accompanied by zero or more intermediate operations.

Points to remember:

– It converts the normal list to a stream
– It is used to process data using filter, map and other, the final output can be collected to form a list

– It doesn’t manipulate original data, instead creates a new stream
– It provides various stream operation such as map, filter and more
– An element in a stream is always traversed exactly once.
– It does the stream lazily as it doesn’t traverse until the terminal operation doesn’t get executed

-It forms a pipeline where intermediate operations and terminal operations are chained together

 

There are two ways in Collection interface to produce a Stream:

stream() -> It returns a sequential stream
parallelStream() ->  Returns a parallel stream. It utilizes the multiple cores of the computer by creating multiple threads to form sub-streams and assigns them given tasks which execute in parallel.

A stream can be split into two operations. An intermediate operation where all the manipulation is done and a terminal which produces the end result.

 

Stream Source or Create a Stream

A source might represent an array, collection and other. Another way is, to create a stream and do the further opertion on that particular stream.

Create Streams

  • Stream.of

A static method that returns a squence of ordered stream.

Stream.of(val1,val2 .. ......)

Code Example :

public class CreateStreams {

    public static void main(String[] args) {
// Creating Stream of Characters
        Stream<Character> characterStream = Stream.of('P', 'R', 'O', 'G', 'R', 'A', 'M', 'M', 'E', 'R', 'B', 'A', 'Y');
// Now Printing it as a word
        characterStream.forEach(singleCharacter -> System.out.print(singleCharacter));
    }
}

Output:

PROGRAMMERBAY

One can also create Stream of array with Stream.of() method.

For example:

public class CreateStreams {

    public static void main(String[] args) {
        String[] stringArr = new String[]{"This", "is", "Example", "of", "Stream"};
        // Creating Stream of Array
        Stream<String> arrayStream = Stream.of(stringArr);
        arrayStream.forEach(singleString -> System.out.print(singleString + " "));
    }
}

Output:

This is Example of Stream
  • List.stream()

In this, a list acts like stream and all the operations are done, just as normal stream.

Code example :

public class CreateStreams {

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        stringList.add("A");
        stringList.add("list");
        stringList.add("example");
        stringList.add("with");
        stringList.add("Stream");

        stringList.forEach(singleString -> System.out.print(singleString + " "));
    }
}

Output:

A list example with Stream

 

Intermediate Operations

An intermediate operation is an operation that always returns a new stream.

  • Filter()

– It allows us to put conditional checks and filter out specific element or data from the source data in form of a new stream.
– It uses predicate as an argument which always returns a boolean type.

Syntax:

filter(Predicate<? super T> predicate)
  • Map()

– It allows us to manipulate the data source or process the data and get the result from it.

– It maps each element to its corresponding result and provides a new stream.

– It accepts Function as an argument which processes a given input to provide the result.

Syntax:

map(Function<? super T,? extends R> mapper)
  • Sorted

-It sorts a list of elements as per natural order.

-However, one can achieve custom behaviour using Comparator.

Code Example :

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(2);
        integerList.add(12);
        integerList.add(1);
        integerList.add(45);
        integerList.add(9);
        integerList.stream().sorted().forEach(System.out::println);
    }
}

Output:

1
2
5
9
12
45

Terminal Operations

A terminal operation is an operation that returns non-stream values such as Optional, object, collection and more.

  • Reduce()

A reduce method performs a certain operation on each element of a given list and produces a single output value. In simple words, it reduces a list to a single output.

-It takes two arguments, first is identity and the second one is Accumulator.

Identity: It resembles the initial value of the reduction operation and acts as a default output if no data exist in the given list.

Accumulator: It is itself a function that takes two parameters, the first one is partial output and the second argument represents the next element of the list.

Code example :

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(5);
        integerList.add(15);
        Integer sum = integerList.stream().reduce(0,(initialVal, nextElm) -> initialVal + nextElm );
        System.out.println("Sum  : "+sum);
    }
}

Output :

Sum  : 25
  • Collect 

-It is used to translate a stream into a list.

-It simply consolidates all the processed result and returns a list

Syntax:

collect(Collector<? super T,A,R> collector)

Collecting stream data as an array :

toArray() is used to get an array as output after performing intermediate operations.

Code example: 

public class CreateStreams {
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(10);
        integerList.add(12);
        integerList.add(15);
        integerList.add(21);
        integerList.add(24);
        Integer[] intArr = integerList.stream().filter(singleElement -> (singleElement % 5 == 0)).toArray(Integer[]::new);
        for (Integer element :
                intArr) {
            System.out.println("Multiples of 5 : " + element);
        }
    }
}

Output:

Multiples of 5 : 5
Multiples of 5 : 10
Multiples of 5 : 15

Collecting stream data as a list :

collect(Collectors.toList()) is used to get a list as output after performing intermediate operations.

Code example: 

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(10);
        integerList.add(12);
        integerList.add(15);
        integerList.add(21);
        integerList.add(24);
        List<Integer> intList = integerList.stream().filter(singleElement -> (singleElement % 5 == 0)).collect(Collectors.toList());
        for (Integer element :
                intList) {
            System.out.println("Multiples of 5 : " + element);
        }
    }
}

Collecting stream data as a Map:

collect(Collectors.toMap() is used to get a Map as output after performing intermediate operations.

Code example: 

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(10);
        integerList.add(12);
        integerList.add(15);
        integerList.add(21);
        integerList.add(24);
        Map<Integer,Integer> intMap = integerList.stream().filter(singleElement -> (singleElement % 5 == 0)).collect(Collectors.toMap(key -> key / 5 , value -> value));
        System.out.println("Map " + intMap);
    }
}

Output:

Map {1=5, 2=10, 3=15}
  • forEach

-Loop through each element of the given stream. It is a new feature provided in Java 8.

Syntax

forEach(Consumer<? super T> action)

 

 

Filter and forEach program example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList(Arrays.asList(5,10,50,15,30,40));

        list.stream().filter(singleEelement -> (singleEelement > 30)).forEach(element -> System.out.println("All value greater than 30 :- "+element));
    }
}

Output:

All value greater than 30 :-50
All value greater than 30 :-40

Explanation:

Above code,  filter method is creating a stream in which only values that are greater than 30 is present, then after, simply printing it over the screen using forEach() method.

 

Map and Collect program example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList(Arrays.asList(5,10,50,15,30,40));

      List newList =  list.stream().map(singleEelement -> singleEelement+5).collect(Collectors.toList());

    newList.forEach(element -> System.out.println(element));
    }
}

Output:

10
15
55
20
35
45

 

Explanation:

Above code,  map method is creating a stream in which each element is incremented by 5 are present, then after, simply converting it to list.

]]>
https://programmerbay.com/stream-in-java-8-with-example/feed/ 0
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
What are the main features of Java 8 ? https://programmerbay.com/what-are-the-main-features-of-java-8/ https://programmerbay.com/what-are-the-main-features-of-java-8/#respond Sun, 14 Jun 2020 15:46:26 +0000 https://programmerbay.com/?p=6428 From 2019, Oracle announces a new version of Java between every 6 months interval and the current version of Java is 14 and they would soon release Java 15. However, Java got its major changes or upgrades with Java 8 which was released back in March 2014.

Prior to Java 8, Java was an object-oriented programming language. Comparing to Java, languages like Python and Scala require less code as they support functional programming and on other hand, Java requires class and object to do the same task and requires more lines of code.

Due to this reason, people started shifting to these type of languages.

In order to compete with others, it was essential to have introduced support for functional programming

Looking at this, Java developers came to the decision of enabling functional programming in Java, focusing on concise code structure. As a result, Java 8 came up with major features to support functional programming.

These features are the main features introduced in Java 8 :

  • Lambda Expression and Functional Interface
  • Stream API
  • Introduction of Default Methods and Static Methods in an Interface
  • Nashorn Javascript Engine
  • Predefined Functional Interface

 Lambda Expressions and Functional Interface

One of the main features of Java 8 is Lambda expression which opens the gate for functional programming. It works in companion with a functional interface. A lambda expression can be defined as an anonymous function that represents an instance of a functional interface.

On the other hand, a functional interface is an interface that consists exactly one abstract method that later, referenced with lambda expression.

@FunctionalInterface annotation is used to tell the compiler that this interface is intended to be functional interface, if any criteria get violated the compiler would trigger compile-time error. It is not mandatory to put the annotation, indeed, it is a good practice though.

It concise and reduces the complexity of the code.

Stream API

java.util.stream package brought in Java 8 introduces the concept of stream. It accepts a collection of objects either sequentially or in a parallel manner and forms a stream where each element go through intermediate operations and the terminal operation.

 

Introduction of Default Methods and Static Methods in an Interface

After Java 8, the interface now supports non-abstract methods and static methods. Non-abstract method, we mean default methods.

A default method allows adding a new feature in form of a method without affecting the implementing classes.

It means that classes that implement that interface are not compulsorily required to override the default method but a specific class that required it can.

Another feature was the Static method, now one can also write a static method within an interface. But it doesn’t directly available to implementing classes, they are required to call by using interface name. for example interfaceName.method()

Nashorn JavaScript Engine

Now an improved JavaScript engine, named Nashorn is proposed in Java 8 that provides better performance than already existing Rhino. It is used to allow embedding JavaScript in Java-based applications. One can be used it either through command-line tool or programmatically

However, It would soon be deprecated and GraalVM would replace it

Predefined Functional Interface

Java provides a bunch of predefined functional interface that resides in java.util.function package. Each and every predefined functional interface has its own characteristics. Some of these are predicate, consumer, supplier and function.

  • Predicate : For conditional checks
  • Function : For input processing
  • Consumer : For consuming input
  • Supplier : For supplying output

 

]]>
https://programmerbay.com/what-are-the-main-features-of-java-8/feed/ 0