Java 8

Java 8 Programming Language Enhancements

Java 8 provides following features for Java Programming:

  • Lambda expressions,
  • Method references,
  • Functional interfaces,
  • Stream API,
  • Default methods,
  • Base64 Encode Decode,
  • Static methods in interface,
  • Optional class,
  • Collectors class,
  • ForEach() method,
  • Nashorn JavaScript Engine,
  • Parallel Array Sorting,
  • Type and Repating Annotations,
  • IO Enhancements,
  • Concurrency Enhancements,
  • JDBC Enhancements etc.

Functional Interface

Default and static methods in Java 8 interfaces offer a powerful way to extend interfaces without breaking existing code1.Differences between default and static methods in Java 8 include123:
  • Default methods provide default implementations that can be optionally overridden by implementing classes, while static methods allow interfaces to include utility methods.
  • Default methods can be overriden in implementing class, while static cannot.
  • Static method belongs only to Interface class, so you can only invoke static method on Interface class, not on class implementing this Interface.
  • Both class and interface can have static methods with same names, and neither overrides other!

Java Lambda Expressions

Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

Functional Interface

Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.


  1. To provide the implementation of Functional interface.
  2. Less coding.
  1. (argument-list) -> {body}  

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.


@FunctionalInterface  //It is optional  

interface Drawable{  

    public void draw();  

}  

public class LambdaExpressionExample2 {  

    public static void main(String[] args) {  

             Drawable d2=()->{  

            System.out.println("Drawing "+width);  

        };  

        d2.draw();  

------------------------------------------------------------

 Sayable s=()->{  

        return "I have nothing to say.";  

    };  

    System.out.println(s.say());  

------------------------------------------------------------

 Sayable s1=(name)->{  

            return "Hello, "+name;  

        };  

        System.out.println(s1.say("Sonoo"));  

---------------------------------------------------------------

  list.forEach(  

            (n)->System.out.println(n)  

        );  

--------------------------------------------------------------

 Runnable r2=()->{  

                System.out.println("Thread2 is running...");  

        };  

        Thread t2=new Thread(r2);  

        t2.start();  

    }  

}  

======================================================

Java Functional Interfaces

An Interface that contains exactly one abstract method is known as functional interface. It can have any number of default, static methods but can contain only one abstract method. It can also declare methods of object class.

Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. It is a new feature in Java, which helps to achieve functional programming approach.

------------------------------------------------------------------------------------

@FunctionalInterface  

interface sayable{  

    void say(String msg);  

}  

public class FunctionalInterfaceExample implements sayable{  

    public void say(String msg){  

        System.out.println(msg);  

    }  

    public static void main(String[] args) {  

        FunctionalInterfaceExample fie = new FunctionalInterfaceExample();  

        fie.say("Hello there");  

    }  

}  

----------------------------------------------------------------------------------------

Java Predefined-Functional Interfaces

Java provides predefined functional interfaces to deal with functional programming by using lambda and method references.

You can also define your own custom functional interface. Following is the list of functional interface which are placed in java.util.function package.

InterfaceDescription
BiConsumer<T,U>
It represents an operation that accepts two input arguments and returns no result.
Consumer<T>
It represents an operation that accepts a single argument and returns no result.
Function<T,R>
It represents a function that accepts one argument and returns a result.
Predicate<T>
It represents a predicate (boolean-valued function) of one argument.
BiFunction<T,U,R>It represents a function that accepts two arguments and returns a a result.
BinaryOperator<T>It represents an operation upon two operands of the same data type. It returns a result of the same type as the operands.
BiPredicate<T,U>It represents a predicate (boolean-valued function) of two arguments.


========================================================================

Java 8 Stream

Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package.


Stream provides following features:

  • Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations.
  • Stream is functional in nature. Operations performed on a stream does not modify it's source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.
  • Stream is lazy and evaluates code only when required.
  • The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

You can use stream to filter, collect, print, and convert from one data structure to other etc. In the following examples, we have apply various operations with the help of stream.

--------------------------------------------------------------------------------

List<Float> productPriceList2 =productsList.stream()  

                                     .filter(p -> p.price > 30000)// filtering data  

                                     .map(p->p.price)        // fetching price  

                                     .collect(Collectors.toList()); // collecting as list  

        System.out.println(productPriceList2);  

-----------------------------------------------------------------------------------

 Stream.iterate(1, element->element+1)  

        .filter(element->element%5==0)  

        .limit(5)  

        .forEach(System.out::println);  

----------------------------------------------------------------------------------

 productsList.stream()  

                             .filter(product -> product.price == 30000)  

                             .forEach(product -> System.out.println(product.name));    

--------------------------------------------------------------------------------------------------

  long count = productsList.stream()  

                    .filter(product->product.price<30000)  

                    .count();  

        System.out.println(count);  

--------------------------------------------------------------------------------------------------

 Set<Float> productPriceList =   

            productsList.stream()  

            .filter(product->product.price < 30000)   // filter product on the base of price  

            .map(product->product.price)  

            .collect(Collectors.toSet());   // collect it as Set(remove duplicate elements)  

        System.out.println(productPriceList);  

----------------------------------------------------------------------------------------------------

 Map<Integer,String> productPriceMap =   

            productsList.stream()  

                        .collect(Collectors.toMap(p->p.id, p->p.name));  

        System.out.println(productPriceMap);  

-----------------------------------------------------------------------------------------------------

No comments:

Post a Comment