Tuesday, April 12, 2016

All about Java stream collect offering

Lets start with a problem statement “Provided collection of employees, we need to find average, max and min age of employee by county”

public static void avgMaxMinEmployeeAgeByCounter() {
    String AVG = "AVG";
    String MAX = "MAX";
    String MIN = "MIN";
    String SUM = "SUM";
    String COUNT = "COUNT";

    List<Employee> employees = Employee.EMPLOYEES;//LIst of all employees, pojos
    // Mapping country name to average, max, min age of employee
    Map<String, Map<String, Double>> summary = new HashMap<>();

    for(Employee e: employees) {
        if(summary.containsKey(e.getCountry())){
            Map<String, Double> map = summary.get(e.getCountry());
            map.put(SUM, (map.get(SUM) + e.getAge()));
            map.put(COUNT, map.get(COUNT) +1);
            map.put(MAX, map.get(MAX) < e.getAge() ? e.getAge():map.get(MAX));
            map.put(MIN, map.get(MIN) > e.getAge() ? e.getAge():map.get(MIN));
        } else {
            Map<String, Double> map = new HashMap<>();
            map.put(AVG, Double.valueOf(e.getAge()));
            map.put(MAX,Double.valueOf(e.getAge()));
            map.put(MIN, Double.valueOf(e.getAge()));
            map.put(SUM, Double.valueOf(e.getAge()));
            map.put(COUNT, Double.valueOf(1));
            summary.put(e.getCountry(), map);
        }
    }
    //Printing result
    Set<String> keySet = summary.keySet();
    for(String country: keySet) {
        System.out.println(country);
        System.out.println("\t Average "+summary.get(country).get(SUM)/summary.get(country).get(COUNT));
        System.out.println("\t Max "+summary.get(country).get(MAX));
        System.out.println("\t MIN "+summary.get(country).get(MIN));
    }
}


Output ::
US
    Average 31.8
    Max 45.0
    MIN 25.0
IND
    Average 30.0
    Max 30.0
    MIN 30.0

We have been writing so many lines of code till Java 8 stream API. Whole perceptive of providing solution for a problem has changed now. Instead of imperative way, Java 8 stream API gives of flexibility of declarative programming. Just let the machine know what you want, instead of giving instructions to how to get it calculated. Considering above problem, we need NOT to instruct how to perform group by, calculate min , max or average.

Lets see how can we solve same problem using Java8 stream’s collect operation

Map<String, DoubleSummaryStatistics> collect = Employee.EMPLOYEES
    .stream()
    .collect(Collectors.groupingBy(Employee::getCountry, Collectors.summarizingDouble(Employee::getAge)));

collect.keySet().stream().forEach(country-> {
    System.out.println(country);
    System.out.println( "\t Average - " + collect.get(country).getAverage());
    System.out.println( "\t Max - " + collect.get(country).getMax());
    System.out.println( "\t Min - " + collect.get(country).getMin());
});

Output:
IND
Average - 30.0
Max - 30.0
Min - 30.0
US
Average - 31.8
Max - 45.0
Min - 25.0

We can see no of code lines reduces to less than half. Here API of interest is ‘collect’, it is called terminal operation. The argument passed to collect is an object of type java .util.stream.Collector. What does a Collector object do? It essentially describes a recipe for accumulating the elements of a stream into a final result. The Collector provides many recipe to consolidate streams like

  • transform stream to list, set etc
  • grouping stream by any attribute
  • Partitioning
  • multiple grouping
  • summarizing

In above example, we are using Collectors.groupingBy to group the stream of employees by first country and then summarizing each of group of records to find average, min, max. Its so simple !!

I have gone through most of the “collect” offering and applied to typical grouping/summarizing problem. For example

  • Employee count by country or city
  • Get employee name with highest salary in given country
  • Partition employee by employment mode by county

You can find complete code sample in my github repository https://github.com/yogeshdevatraj/java8/blob/master/StreamAPIPrj/src/com/stream/EmployeeFactory.java

Sunday, March 13, 2016

Utilizing ES6 Generator

I am going through Mozilla documentation about the Iterator and Generator concept introduced in ECMAScript6. Here is the overview as per Mozilla JS guide

Processing each of the items in a collection is a very common
operation. JavaScript provides a number of ways of iterating over a
collection, from simple for loops to map() and filter(). Iterators and
Generators bring the concept of iteration directly into the core
language and provide a mechanism for customizing the behavior of
for…of loops.

This post is not about how it works, it is better explained at Mozilla JS guide.

I have tried to apply the JS generator for one of the our day to day code. I think it is better suitable for lazy traversing and evaluating each item and proceed further if required. A common example comes in my mind is the tree traversing. I have implemented Depth First Search ( pre-order) using generator.

Consider the scenario where you need to traverse the tree node, evaluate/process the node and go further for next node. The code is as simple as below

var tree = getTree();
for (let node in tree.dfs()){
    // process node.
}

Isn’t above code super simple to understand, all traversing code it hidden, no need to manipulate the index/pointer etc.

Here I wrote simple traversing code that uses generator that return each node one by one.

function constructTree(values) {    
    return {
        dfs: function* (index) {
            if (!index) index = 0;
            yield values[index];
            if((2 * index + 1) < values.length)
                yield* this.dfs(2 * index + 1);
            if((2 * index + 2) < values.length)
                yield* this.dfs(2 * index + 2);

        }
    }
}

var tree = constructTree(values); 
for (let val of tree.dfs()) { 
   //process val
}

Here I am expecting the tree structure in an array. You can notice new syntax has been introduced function* to represent iterator/generator for the given JS object.

A generator is a special type of function that works as a factory for
iterators. A function becomes a generator if it contains one or more
yield expressions and if it uses the function* syntax.

The complete example is available at fiddle

Sunday, September 13, 2015

Looping & Closure

Here is simple code to dynamically create set of buttons that greet in different languages.

document.body.onload =  createButtons;
function createButtons() {
    var greetings = [
        {lang:'English', msg:'Good Morning !!'},
        {lang:'German', msg:'Guten Morgen !!'},
        {lang:'French', msg:'Bonjour !!'},
        {lang:'Finnish', msg:'Huomenta !!'}
    ];
    document.createElement('h1');
    console.log(greetings);
    for(var i=0;i<greetings.length; i++){
        var greet = greetings[i]
        var input = document.createElement("button");
        input.appendChild(document.createTextNode(greet.lang));
        input.setAttribute('class','btn btn-default btn-lg');
        input.onclick = function(event){
            alert(greet.msg);
        };
        document.body.appendChild(input);
    }
}

Pretty simple, looping through array of objects and adding buttons with language label and greet message in respective language as alert dialog on click action.
Here is the final html looks like

Multi-language greeting buttons

Many of you guys might already have understood the issue with above code. One can easily notice that all button greet you in ‘Finnish’.

Miss-matched greet message

Why ?
It is all because of onclick function has become ‘closure‘.

input.onclick = function(event){
            alert(greet.msg);
};

It carries all the local variable that are in scope, here ‘greet’ object . As the value of ‘greet’ object change in every loop, all references in onclick callback closures also get same reference. So final reference in all the callback will be the last value of the greet in the loop.
I need not explains more about this typical problem, here is complete explanation available .

How to solve ?
One way to fix this issue by using functional scope. Lets wrap the callback function into another immediately invoked function with message as parameter. In this self invoked wrapper function with message as parameter, the callback function gets bind to wrapper function parameter , not the outside looping variable.

input.onclick = (function(msg){return function(event){
            alert(msg);
}})(greet.msg);

ES6 Way
ES6 has brought cleaner solution for this issue, let statement.

The let statement declares a block scope local variable, optionally
initializing it to a value.

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
In our script, we just need to use let statement instate of var while storing array object.

for(var i=0;i<greetings.length; i++){
        /*Using let instate of var*/
        let greet = greetings[i];
        var input = document.createElement("button");
        input.appendChild(document.createTextNode(greet.lang));
        input.setAttribute('class','btn btn-default btn-lg');
        input.onclick = function(event){
            alert(greet.msg);
        };
        document.body.appendChild(input);
  }

So all our greet button are started displaying messages in there respective languages

enter image description here

Here is the complete code snippet http://jsbin.com/xekexij/edit?html,output

Friday, April 10, 2015

NPE as well as Null check free code ... Really ?

NPE as well as Null check free code … Really ?

NPE

Is this how your Java code review start ? NPE is always nightmare for a Java developer. Lets not discussion to much and jump on an usual Java code snippet

public interface Service {  
    public boolean switchOn(int timmer);
    public boolean switchOff(int timmer);
    //Other controls 
}
public class RefrigeratorService implements Service {
// ...
}
public class HomeServices {
    private static final int NOW = 0;
    private static HomeServices service;

    public static HomeServices get() {
        //Null Check #1
        if(service == null) {
            service = new HomeServices();
        }
        return service;
    }

    public Service getRefrigertorControl() {
        return new RefrigeratorService();
    }

    public static void main(String[] args) {
        /* Get Home Services handle */
        HomeServices homeServices = HomeServices.get();
        //Null Check #2
        if(homeServices != null) {
            Service refrigertorControl = homeServices.getRefrigertorControl();
            //Null Check #3
            if (refrigertorControl != null) {
                refrigertorControl.switchOn(NOW);
            }
        }
    }
}

Above few lines of code snippet has multiple null checks, of-course to make it robust against all possible cases. Well that is necessary but is there any better way … ? It was so often that I uses Eclipse template to surround piece of code with if condition for null check

Eclipse template for NPE check

Is there any better way ?

Well Yes !!!.
Java 8 has introduced java.util.Optional<T> . It is a container that may or may not hold non-null value. Java 8 have given safer way to handle object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

In above example we have home service factory that returns handle to multiple appliances available in the home. But these services may or may not available/functional, it means it may result NullPointerException. Instead of adding null if condition before using any service, let wrap it in to Optional<Service>.

Wrapping to Option<T>

Lets consider method to get reference of service from factory, instead of returning the service reference wrap it with Optional. It let the API user know that the returned service may or may not available/functional, use defensively

public Optional<Service> getRefrigertorControl() {
    Service s = new  RefrigeratorService();
    //...
    return Optional.ofNullable(s);
}

As you see Optional.ofNullable() provides easy way to get the reference wrapped. There are another ways to get reference of Optional , either Optional.empty() & Optional.of(). One for returning empty object instead of retuning null and other to wrap non-nullable object, respectively.

So how exactly it helps to avoid null check ?

Once you have wrapped reference object, Optional provide may useful methods to invoke methods on wrapped reference without NPE.

Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);

Optional.ifPresent invoke the given Consumer with reference if it is non-null value otherwise does nothing.

@FunctionalInterface
public interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.

We user ternary operator very often for checking null condition and return alternative value or default value. Optional provides another way to handle same condition without checking null. Optional.orElse(defaultObj)returns defaultObj if the Optional has null value. Lets use this in our sample code

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

Now HomeServices.get() does same thing but in better way. It checks whether the service is already initialize of not. If it is then return same or create new New service. Optional<T>.orElse(T) helps to return default value.

Finally here is our NPE as well as null check free code

import java.util.Optional;
public class HomeServices {
    private static final int NOW = 0;
    private static Optional<HomeServices> service;

    public static Optional<HomeServices> get() {
        service = Optional.of(service.orElse(new HomeServices()));
        return service;
    }

    public Optional<Service> getRefrigertorControl() {
        Service s = new  RefrigeratorService();
        //...
        return Optional.ofNullable(s);
    }

    public static void main(String[] args) {
        /* Get Home Services handle */
        Optional<HomeServices> homeServices = HomeServices.get();
        if(homeServices != null) {
            Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
            refrigertorControl.ifPresent(HomeServices::switchItOn);
        }
    }

    public static void switchItOn(Service s){
        //...
    }
} 

Source :
http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
Cartoon Image source : http://geek-and-poke.com/

Saturday, April 4, 2015

Java doesn't have "Diamond" problem : Really ..?

Java doesn’t have “Diamond” problem : Really ..?

We have been confidently telling that Java doesn’t have diamond problem even if it support multiple inheritance.

In object-oriented programming languages with multiple inheritance and
knowledge organization, the diamond problem is an ambiguity that
arises when two classes B and C inherit from A, and class D inherits
from both B and C.

But do you that the diamond problem is now there in newly introduced Java 8. It is because of the introduction of default methods in Interface. In Java8 Interfaces not only have method declaration but their default implementation. Any class implementing can either use default implementation from interface or provide its own implementation. Since Java class can implement multiple interfaces it is possible that two interfaces has same default methods, that brings diamond problem.

How do we overcome diamond problem ?

Consider following code snippet

public interface InterfaceA {
    default long calculateArea(long height, long width) {
        return height * width;
    }
}
public interface InterfaceB {
    default long calculateArea(long height, long width) {
        return height * width;
    }
}
public class ImplClass implements InterfaceA, InterfaceB {

    public static void main(String[] args) {
        ImplClass obj = new ImplClass();
        System.out.println(obj.calculateArea(10, 10));
    }
}

Trying to compile this code, Java8 compiler throws errors

Duplicate default methods named calculateArea with the parameters
(long, long) and (long, long) are inherited from the types InterfaceB
and InterfaceA

Java8 compiler forces the implementing class to choose either of default implementations from Interfaces or provide its own implementation. The final code would be

public class ImplClass implements InterfaceA, InterfaceB {
    /* Compiler forces to provide implementation for ambiguous 
     * default methods from multiple imterfaces */
    public long calculateArea(long height, long width) {
        /*Programmer have option to either select one the default 
         * implementation
         * */
        //return InterfaceA.super.calculateArea(height, width);
        //OR
        //return InterfaceB.super.calculateArea(height, width);
        //OR
        //Own implementation 
        return height * width * 2;
    }
    public static void main(String[] args) {
        ImplClass obj = new ImplClass();
        System.out.println(obj.calculateArea(10, 10));
    }
}

Why do we need default methods…?

A default method is a method declaration and implementation, and it is
denoted with the default keyword preceding the declaration. Any class
that extends an interface containing a default method can choose to
implement and override the default implementation or simply use the
default implementation.

The default methods are being introduced to have additional methods in existing without breaking existing code base ( backward compatibility) .You can to add a new method to an existing interface without breaking backward compatibility with other code.Develop a default method (a.k.a. defender method) within the interface so that any classes implementing the interface are not required to provide an implementation of the new method.

Why now … ?

You must be thinking why do Java 8 needs to introduce the default methods, although this problem is there from very version of Java. The main motive could be introduction of Lambda expressions

lambda expressions are a convenient way to create anonymous functions.
They provide an easy way to create a single method interface using an
expression or series of statements. Lambda expressions are built upon
functional interfaces, which are interfaces that contain a single
abstract method.They can be applied in many different contexts, ranging from simple anonymous functions to sorting and filtering Collections. Moreover, lambda expressions can be as signed to variables and then passed into other objects.

Default methods were added in order to provide a way to change interfaces without breaking backward compatibility. Many interfaces needed to be changed to accommodate Java 8 API updates, and in doing
so, these interfaces would possibly break functionality of code that was written for prior releases of Java. By adding default methods to interfaces, engineers were able to add new functionality to existing interfaces without breaking the code that relied on those interfaces.

The main purpose of this post is to introduce ‘Default methods’ in Java8, but I though it would be interesting to start with this article with consequences. It is very fun fact that one of the base we defend Java over other OOPS languages like C++, it no more valid :)
So keep in mind that Java is not diamond problem proof.

Saturday, January 31, 2015

Overloaded function in Javascript


Coming from Java background, it is happened to be searched java language constructs while coding javascript. One of such construct is overloaded methods/function. Take a look following code snippet
 
//Normal sum
var intergerSum = sum(10, 20);
//Expecting item price sum
var objectSum = sum(
  {item_id:'01',name:'abc', price:100},
  {item_id:'02',name:'xyz', price:200}
);

As per above code snippet, implementation of ‘sum’ has been abstracted from the user. In the world of type safe language like Java, it is very straight forward, but in case of javascript we need to have our custom implementation. Lets see how can we achieve above in javascript.
Lets start with defining a constructor function which introduce a common function to all our custom object so that we can extract integer value for summation.

//constructor function to introduce new function to custom object
function item(options) {
  var instance = Object.create(item.prototype);
  for(property in options) {
      instance[property] = options[property];
      instance[property] = options[property];
  }
  return instance;
}

item.prototype = {
  valueOf : function() {
    console.log('Inside prototype');
    return this.price;
  },
  type: 'item'
};

As per above code snippet, item() construction function return new object with special function valueOf(). Lets execute our initial code snippet with little modification

//Normal sum
var integerSum = sum(10, 20);
//Expecting item price sum
var objectSum = sum(
  item({item_id:'01',name:'abc', price:100}),
  item({item_id:'02',name:'xyz', price:200})
);
console.log(integerSum);//=> 30
console.log(objectSum);//=> 300

So we have overloaded sum() which seamlessly return summation for literal to custom object.

Do you know Javascript … Try these puzzle

Do you know Javascript … Try these puzzle

Javascript is one the most miss-understood language among developers. Everyday I learn new lesson about it.While going through few articles I thought of following JS language puzzles.

Handling Array
var days = ['Monday', 'Tuesday','Wednesday','Thursday','Friday', 'Saturday'];
var  length = days.length;
console.log('No of days are ' + days.length);
//Opps we missed Sunday, lets add it
days[++length] = 'Sunday';

console.log('Final no of days are ' + days.length);

It is obvious that no of days are 7…. is it ?

Written with StackEdit.


  1. StackEdit is a full-featured, open-source Markdown editor based on PageDown, the Markdown library used by Stack Overflow and the other Stack Exchange sites.
  2. Here is the text of the footnote.