Showing posts with label Java 8. Show all posts
Showing posts with label Java 8. Show all posts

Friday, August 11, 2017

What's so special about Java 8 stream API

Java 8 has added functional programming and one of the major addition in terms of API is, stream.

A mechanical analogy is car-manufacturing line where a stream of cars is queued between processing stations. Each take a car, does some modification/operation and then pass it to next station for further processing.


Main benefit of stream API is that, now in Java (8) you can program at higher level of abstraction. So you can transform stream of one type to stream of other type rather than processing each item at a time (using for loop or iterator). With this Java 8 can run a pipeline of stream operations on several CPU cores on different components of the input. This way you are getting parallelism almost free instead of hard work using threads and locks.

Stream focuses on partitioning the data rather than coordinating access to it. 

                                              Vs


Collection is mostly about storing and accessing the data, whereas stream is mostly about describing computation on data. 




Saturday, February 18, 2017

Java 8 method references

This post talks about one of the coolest feature of Java 8; method references!

Methods are no longer second class values in Java 8. Just like object references which can be passed around as values, methods can also be passed around as values. To achieve this, Java 8 provides notation, :: (along with lambda, off course)

You might argue that, lambda functions do the same thing. And you are write to a great extent. The only fundamental difference is that, this way you can simply refer to a method without writing the full body of the method (as we do in lambda).

Lambda vs Method Reference
Function<Double, Double> square = (Double d) -> d * d;   //lambda
Function<Double, Double> square = Arithmatic::square    //method reference

Arithmatic::square is a method reference to the method getSquare defined in the Arithmatic class. Brackets are not needed because we aren't calling the method actually.

(String s) -> System.out.println(s)     //lambda
System.out::println                            //method reference

In lambda, you just call the method without it's name but in method reference you explicitly refer it by name. This way, code is more readable.

--
happy functional programming !

Saturday, January 21, 2017

Function as First Class Citizens in Java

Java (in version 8) added support for treating functions as first-class citizens. Before this, Java programmers had to wrap standalone functions with Runnables or other anonymous interface implementation class to be able to refer to them. 

Function as first-class citizen/type/object/entity/value:
Functions can be passed around like any other value!

What this basically means is that-

  •  functions can be passed as arguments to other functions, 
  • functions can be returned as values from other functions, 
  • functions can be assigned to variables 
  • functions can be stored in data structures. 

Before Java 8, Objects and primitives data types were treated as first-class citizens (Classes and Functions were treated as second class as they were not values). But, functions are just as valuable to manipulate and reuse. Java inherited this modern feature from other functional programming languages (like JavaScript, Scala). This will help in improving productivity as programmers now can code at the different level of abstraction. 

Read more in detail about what is first class, here


Lambda expression enables you to provide an implementation of the functional interfaces (which has only one method ) directly inline and they treat the whole expression as an instance of the functional interface. Below, we will see how lambda enables functional interfaces to be treated as first-class objects.


Function As Value

java.util.function package (ref) provides multipurpose functional interfaces which come in handy.


import java.util.function.BiFunction;
import java.util.function.Predicate;

/**
 * Creates Inline lambda functions and stores as variable. And then function can be called directly from variable.
 */
public class FunctionAsValue {
    public static void main(String[] args){
        Predicate<String> predicate = (s) -> s!=null || !s.isEmpty ();
        System.out.println(predicate.test ("geekrai"));

        //static method which confirms to Predicate method signature can be stored in invoked
        Predicate<String> pedicateRef = FunctionAsValue::isNotEmpty;
        System.out.println(pedicateRef.test ("geekrai"));

        //BiFunction accepts two arguments and produces a result
        BiFunction<String, String, String> concat = (s, t) -> s+t;
        System.out.println(concat.apply ("hello", " world"));
    }

    private static boolean isNotEmpty(String s){
        return s!=null || !s.isEmpty ();
    }
}


Output:

true
true
hello world


Function As Parameter




import java.util.function.Function;

/**
 * Illustrates how to pass function as parameter
 */
public class FunctionAsParam {
    public static void main(String[] args){
        //pass function as parameter to transform method
        System.out.println(transform ("geek", "Rai", s -> s.toUpperCase ()));

        Function<String, String> toLower = s -> s.toLowerCase ();

        System.out.println(transform("geek", "Rai", toLower));
    }

    private static String transform(String a, String b, Function<String,String> toUpper){
        if(toUpper != null){
            a = toUpper.apply (a);
            b = toUpper.apply (b);
        }
        return a + b;
    }
}

Output:
GEEKRAI
geekrai

--happy functional programming !!!


Friday, January 6, 2017

Pure Functions

This post discusses one of the important aspects of functional programming, Pure Function using Java example.

Pure functions are side-effect free functions or stateless functions. The output of pure functions depends purely (or completely) on input. What side-effect free basically means is that pure functions should not modify argument as well as any other state variables. 

Now, the obvious question is why is it so important. We will see later how it's one of the important ingredients for functional and Reactive programming. Let take a simple Java class to understand pure functions.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package functional;

import java.util.Random;

public class PureFunction {
 private int state = 420;

 // pure function
 public int addTwo(int x) {
  return x + 2;
 }

 // Impure function
 public int addState(int x) {
  return x + state;
 }

 // Impure Function
 public int randomizeArgument(int x) {
  Random r = new Random(1000);
  return x + r.nextInt(1000);
 }
}

Method, addTwo purely depends on its input/argument. No matter how many times you call it, it will behave in a predictable manner (i.e just add 2 to the argument and return the added number as the response). While the response of the other two methods (addState and randomizeArgument) is not going to be consistent even if it's called with same argument multiple times. The response of method addState depends on the instance variable of the class. If it gets mutated somewhere else, the response of the method will not be consistent. Similarly, the randomizedArgument method response will vary depending on the random value.

Let's cover some of the important points

  • If a pure function references any instance variable of the class, then that instance variable should be declared as final.
  • Pure functions help in highly concurrent and scalable environment by making the behavior predictable. 
  • You get parallelism free of cost if your method doesn't access a shared mutable data to perform its job. 

--happy learning !!!


Wednesday, December 9, 2015

Transform collection of one object to another using Java 8 Streams

Few days back, I wanted to convert a list of value objects to another list of ORM/entity objects.  It's a very commonly occurring scenario; oh BOY, streams API works like a charm!

If you are working on application having layered or distributed architecture, this scenario is quite common. When data moves from client/UI to get persisted it gets transformed multiple times. Let's see how it can be done effectively in Java 8 using streams API.



public class City {
 private String name;
 private String zipCode;
 
 //other attribute, setter/getters
}

public class CityOrm {
 private String name;
 private String zipCode;
 private long id;
 
 public CityOrm(City city){
  //construct this using City instance
 }
 //other attribute, setter/getters
}


Please note that CityOrm has a constructor. So transforming or converting a City instance to CityOrm instance is not an issue.  

Problem is:

You have a collection of City; you need to convert it into a collection of CityOrm. 


Before Java 8

 List<City> cities = getItFromSomeWhere();
List<CityOrm> citiesOrm = new ArrayList<>();
for(City city : cities){
citiesOrm.add(new CitiyOrm(city));
}


Java 8 / Streams API

   List<City> cities = getItFromSomeWhere();
   List<CityOrm> citiesOrm = cities.stream()
          .map(city -> new CityOrm(city))                   .collect(Collectors.toList());


stream() method converts the list of City instances into a stream and then map() method goes through each city and by calling appropriate constructor converts it to another type (i.e. CityOrm). And finally, collect() method converts the stream back to a list. 
So Stream API definitely saved a couple of lines (excuse the spread due to formatting). 
                  

Wednesday, June 24, 2015

Java 8 Date and Time API

Any experienced Java programmer would agree that the Date/Calendar API before Java 8 was confusing and inconsistent. It also has some design flaws. I have found myself in confusing situations like whether to use java.util.Date or java.util.Calendar API. Most of the cases, I used to google for code snippet and quickly get rid of the problem. And in some other cases which required lot of date/time manipulation, I used third-party libraries (like Joda-time API).

It's pleasing to see that, Java designers finally addressed this pain point and introduced a new set of API. I have tried to quickly cover major API and their usage with simple examples. This post will give you quick start to understand new classes added in package java.time.

java.time.LocalDate

An instance of this class is an immutable object which just stores date information, i.e. year, month and day. It doesn't store the time and time zone. LocalDate provides factory methods to fetch the system current date or refer a specific date.

LocalDate independenceDay = LocalDate.of(1947, 8, 15); //15th Aug 1947
LocalDate parsedDate  = LocalDate.parse("2015-01-31");

LocalDate today = LocalDate.now();       //2015-06-24
int day        = today.getDayOfMonth();  //24
int month      = today.getMonthValue();  //6
Month mon      = today.getMonth();       //JUNE
int year       = today.getYear();        //2015
DayOfWeek days = today.getDayOfWeek();   //WEDNESDAY
int len        = today.lengthOfMonth();  //30

java.time.LocalTime

Similar to LocalDate, LocalTime represents just the time without any date and time zone information. 

LocalTime specificTime = LocalTime.of(12, 45, 59);
LocalTime parseTime = LocalTime.parse("13:45:20");
LocalTime now =  LocalTime.now();
int hour      = now.getHour();
int minute    = now.getMinute();
int seconds   = now.getSecond();

int nanoSec = now.getNano();  //gets nano of second

java.time.LocalDateTime

As the name suggests, LocalDateTime represents both date and time, without any time zone information. It can also be created by combining LocalDate and LocalTime. 

LocalDateTime NowDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now());   //2015-06-24T17:58:29.557
LocalDateTime specificDateTime = LocalDateTime.of(2015, Month.JANUARY, 18, 13, 45, 20); //2015-01-18T13:45:20
LocalDateTime aTime = LocalDate.now().atTime(13, 45, 20);   //2015-06-24T13:45:20

Date and Time for machines

All approaches discussed above are more suitable for humans, but machines will prefer a unique number which abstracts date and time information (similar to the way it was done in java.util.Date API). 

java.time.Instant represents the number of seconds passed since the Unix epoch time (midnight Jan 1, 1970, UTC). The Instant class also provides a now factory method to capture current timestamp. This API also supports nanoseconds precision which was not there in previous date/time/calendar API.

Instant timeStamp = Instant.now();   //2015-01-18T13:45:20
long second = timeStamp.getEpochSecond();  //1435149943
long nano = timeStamp.getNano();  //341000000, total number of nano seconds since getEpochSecond


Tuesday, April 14, 2015

Functional Interfaces in Java 8

This post compliments the previous post where I have discussed about Lambda Expression, link. To unleash the power of lambda, a good understanding of functional interface is must. Let's briefly cover it:

Functional Interface

Functional Interfaces are those Interfaces in Java which has only one abstract method. Interfaces having single method (like Runnable, Callable, Comparable etc) existed in Java even before version 8. It's just that this new term was coined in context of Lamda Expression.

Functional interfaces are pre-condition for Lambda expression. Lambda expression allows you to provide the implementation of the method inline as an anonymous implementation of the interface.   Before Java 8, programmers used to provide implementation of functional interfaces using Anonymous class (which let you declare and instantiate the class at same time). Below is mostly commonly seen way to implement a Runnable task. 

  Runnable task = new Runnable(){
    public void run(){
        //implementation...bla bla.
  }
};

If interface is NOT functional, implementing the interface or providing anonymous implementation as shown above are two options. But if there is just one abstract method in the interface, Java 8 provides a more succinct and less verbose style to provide implementation. Java also introduces an optional annotation to mark an interface as functional. 


@FunctionalInterface
public interface MyFunctionalIf {
public String doSomething(String);

}

Annotation is used to indicate that the interface is intended to be functional interface. It's not mandatory to use the annotation but definitely a good practice. This annotation will also prevent you to accidentally add another method and break the functional contract of having just a single method. One important point to keep in mind is that default and static methods don't break the functional contract. 
Above interface can be used by implementing it in a concrete class or by providing ad-hoc implementation using anonymous class as shown for Runnable. 

Implementing Functional Interface using Lambdas

Functions were not first class citizen (before Java 8) and you need to have a handle of object to call/use method. Now let's see how lambda changes the implementation of functional interfaces:

Runnable lambdaTask = () -> { //implementation  };
lambdaTask.run();  //using lambda

MyFunctionalIf myFunctionalIf = (String message) ->  "hello "+ message;
myFunctionalIf.doSomething("Sid");   //using lambda

                                                                                   
Now, look how cleaner the functional implementation of the interfaces look. It's very concise, flexible and re-usable.

Please note that in second case, the curly brace as well as return clause is missing (both can be removed if there is only one line in the method body. Even type in argument is optional, so you can ignore String in above lambda expression. Notice that the name of the method is missing in lambda so it is also called as anonymous method

Default Method

Now interfaces can also provide a default methods. Obviously, functional interfaces can also have any number of default methods. You just need to add default keyword in method definition.

List<> interface adds a sort method so that you can sort a list by calling sort method on its instance instead of calling sort method from Collections utility class.

default void sort(Comparator<? super E> c) {
     //implementation 
}

In-built Functional Interfaces Added In Java 8

Imagine creating your own multiple functional interfaces. But, Java helps programmers by providing some reusable functional interfaces out of the box. 

Java designers have created a separate package for same, java.util.funtion.

So do check this package before creating your own functional interfaces. Chances are high that you will find one matching your needs.

---
keep coding !!!

Saturday, March 28, 2015

Lambda Expression in Java 8

Let's go functional!

Lambda Expression (Closure or Anonymous method) is one of the most important additions to Java 8.  In fact, it's the most incredible additions to language in its history; it is going to change the way we write programs in Java.  With this new feature, Java adds one of the modern programming technique, Functional Programming.

This is useful for Functional Interfaces (the interface that requires exactly one method to be implemented). Runnable, Callable, Comparable and other interfaces which just have a single method are called functional interfaces. You can even define your own interface with a single method to unleash the power of Lambdas.

Syntax of Lambda

Lambda consists of 3 parts :
  1. Parenthesized set of parameters
  2. Arrow sign ( -> )
  3. Body in form of single expression or a block 
i.e. (Parameter1 p1, Parameter2 p2)            ->                           { }
       (parameters)                                   (arrow sign)          (method body)

Properties:
  • It doesn't have an explicit name for the method, so it's called an anonymous method as well
  • It can throw Exceptions
  • It's more like a method (and not a class), it has a list of parameter, body and return type
  • It can be passed as an argument to a method and can be stored as a value in a variable

Runnable Implementation without Lambdas

Before going all out on Lambda. Let's see how these interfaces get implemented without it.

Approach 1: Implement the interface

public class MyRunnableImpl implements Runnable{
     @override
     public void run(){
         //TODO: Implementation
     }
}

Approach 2: Using anonymous (inner) class
   
Runnable task = new Runnable(){
    public void run(){
       //TODO: Implementation
   }
};

Approach 2 is better than first but still, it's quite verbose and there is hardly any scope of reusability.

Implementing functional interfaces through Lambda

The compiler knows beforehand that the Runnable interface has only one method to be implemented. So this lack of ambiguity around which method needs to be implemented helps in making the Runnable implementation more compact and efficient using lambdas. 

So using Lambda; above code can be replaced as :

Runnable task = () -> System.out.println("inside run method");
or 
Runnable task = () -> { System.out.println("inside run method"); };

And on similar lines you can implement Callable as well :

Callable<Integer> task = () -> {
       Random r = new Random(101);
       return r.nextInt(101);
};

If the method takes some argument, then they get passed inside parentheses. Let's take case of Comparator interface:


Comparator<String> c = (String a, String b) -> { return a.compareTo(b); };


Before version 8, the lowest level of abstraction in Java was classes. Functions were not treated as the first-class citizen as you need to have an object handle to use functions (functions don't exist without object). But functions are as valuable and important as objects and classes. Programming languages with first-class functions let you find more opportunities for abstraction which means your code is smaller, lighter, more reusable and scalable.

Related Post: Functional Interfaces

---
keep coding !!!