Sunday, 4 June 2017

Java8 - New Features

Interface
  • We can provide implementation to existing/new interfaces by using "default" key word before the method definition
  • Support static methods
  •  
Streams
  • A sequence of elements supporting sequential and parallel aggregate operations.

New Date Time API
  • java.time is the package
  • LocalDate d = LocalDate.of(
    LocalTime t = LocalTime.now(ZoneId.of("Asia/Kuwait"));
    LocalDateTime
    ZoneId.getAvailableZoneIds()
    Instant.now()
Lambdas
  • Enables functional programming, Readable and concise code, Easier to use APIs and libraries, enables support for parallel processing

https://www.youtube.com/watch?v=tfbmYBcq5CM&index=20&list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3#t=2.097395

Programming Pradigms
  • Imperative programming: Programming with variables, lists, for-loops. eg: c
  • Functional programming: In unit of functions eg: excel
  • Object oriented programming: Classes & object eg: java, c#, c++
Java is definitively an Object-Oriented language, but recently it has added support for some functional programming features.

Benefits of Lambdas:
  • Enables Functional programming
  • Readable and concise code
  • Develop APIs and libraries that are easier to use
  • Support for parallel processing
Lambdas are just a functions in isolation(doesn't belog to class). Those functions can be treated as Values.

Examples:
public class TypeInferenceExample{
   public static void main(String[] args){
    printlambda(s->s.length());
    }
   public static void printlambda(StringLengthLambda l){
    System.out.print(l.getLength("hello lambda"));
    }
   interface StringLengthLambda{
    int getLength(String s);
  }
}

public class RunnableExample{
   public static void main(String[] args){
    Thread myThread = new Thread(new Runnable() {

    @Override
    public void run(){ System.out.println("inside runnable"); }
    });
    myThread.run();

    Thread myLambdaThread = new Thread(()->System.out.println("inside runnable"););
    myLambdaThread.run()
}

Functional Interface
    Interface that has only one abstact method is called a Functional interface. Such interfaces can be used for lambda types.

@FunctionalInterface annotation is used to mark the same.


Single Method interfaces are called "Functional Interfaces" or "Single Abstract Method" interfaces.
Lambda Expressions/Functional Expressions/Closures: Functional constructs in an Object Oriented Context-1

Lambda Functions
  • They are simply Anonymous Functions
  • An alternate to anonymous classes with a single method
  • Useful for quick and dirty bits of coding that don't need a class