Thursday 24 July 2014

Java 8 main Feature - Lambda Expressions or Basics of Lambda Expressions


Lambda Expression is newly added feature in Java 8, which is like a Javascript Closure or Scala, where function or reference of a function, together with a referencing environment a table storing a reference to each of the non-local variables of that function. So, we can say Lambda expression is similar to Closure or Scala, but not 100%.

like -
---------------------------------------------
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
--------------------------------------------


So we can say Lambda Expressions, a new language feature, That enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly. 
Lambda expression is short form of writing method, and can be used in multiple ways. syntax is given below-

Lambda Expression syntax    


 (argument...) -> {statement}
Here method name, return type, and access modifier is not require to mention.

above is replica of below in old java

Accessmodifier ReturnType methodname(argument){
 //method statement
}


Lambda can be written in some more ways-
 
() -> 10           
 // no parameter and returns 10 
 
x -> x * x  
 // a number parameter parameter and returns the squared of number
 
(x, y) -> x – y  
   // two numbers parameter and returns their difference 
 
(int x, int y) -> x + y   
//two integers number and returns their sum 
 
(String s) -> System.out.print(s) 

 //string parameter and prints output to console


As you now aware of some basic syntax of Lambda expression so see some expmple below-

-------------------------------------------
String[] array= {"ABC", "BCD", "DEF", "GHI"};
List<String> list=  Arrays.asList(array);
 
new way coding style- 
  list.forEach((item)-> System.out.println(item));
 
old way coding style-
  for (String item: list) {
    System.out.println(item);
  }
------------------------------------------
Method reference is also java 8 feature which you can plug with Lambda expression and get some more shorter way of code. It denote by :: (two colon) operator.
method references; shortcuts that you can use anywhere you would use a lambda. There are four types of method referenc-
  1. Reference to a static method-         ContainingClass::staticMethodName 
  2. Reference to an instance method of a particular object - ContainingObject::instanceMethodName 
  3. Reference to an instance method of an arbitrary object of a particular type - ContainingType::methodName
  4. Reference to a constructor-         ClassName::new
   Example and plug with Lambda by below Comparison-

  As Method Reference                                   As Lambda Expression
  String::valueOf                  (str) -> String.valueOf(str)
  x::toString                      () -> "test".toString()
 String::toString                 (s) -> s.toString()
 String::new                      () -> new String()

---------------------------------------------------------------
//Iterate item by Method reference (::) two colon operator
//by using reference to a static method
  list.forEach(System.out::println);
 
//instance method of object call 
 String x = "test";
 function(x::toString);
------------------------------------------------
 
Anonymous classes also can be replaced with lambda expressions. 
The same thing happens when implementing the Runnable interface
-----------------------------------------------------------
// older style thread example 
new Thread(new Runnable() {
 @Override
 public void run() {
  System.out.println("Thread example");
 }
}).start();
 
// Using lambda expression thread
new Thread(() -> System.out.println("Thread example")).start(); 
---------------------------------------------------------------- 
 
Lambda with Stream
Java 8 added some Stream APIs. java.util.stream.Stream interface.
So, these Collection Stream method can be used by Lambda. like- map, 
filter,limit, max, min, sort and so on.
----------------------------------------
//Old way of coding
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
for(Integer n : list) {
    int x = n * n;  //calculate the square of number
    System.out.println(x);
}
//New way of coding
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
list.stream().map((x) -> x*x).forEach(System.out::println);
Here we are getting the stream() and mapping all the stream element to 
x -> x*x then we are using method reference to print all the squared value.
-------------------------------------------------- 
 
That's it about Lambda!!!!

Tuesday 22 July 2014

Java - IS-A and Has-A Relationship or Inheritance vs Association (Composition and Aggregation)

IS-A relationship

Inheritance is provide us the re-usability feature. Let's take one example we have a Human Category, so either boy can be human or girl can be human and each human has some common activity like eat(), walk(), see() apart from common activity boy has some activity like run() similarly girl has skip() and cookFood().
see more detail on below diagram-



So Boy and Girl both denoted by Human in common. and this is called inheritance and this relationship human--boy  and human --girl called IS-A relationship. so in short you can say Boy IS-A Human similarly Girl Is-A Human. so IS-A relationship always give re-usability feature.And In java we can achieve either by extends(In case of class) keyword or implements(in case of interface). 

In UML we can use arrow to show relationship between parent and child.
in this case we will say Boy-------------->Human

Has-A relationship (Association)

Has-A means an instance of one class “has a” reference to an instance of another class or another instance of same class.There is no specific keyword to implement HAS-A relationship but mostly we are depended upon “new” keyword. 
It can be two type-
  1. Aggregation
  2. Composition
Aggregation means weak has-a relationship between object. Let take a example if you have car and car has a headlight, and here headlight object removed from the car then also car can be run. i.e. in this type of relationship both object are loosely associated. In other word, It is an association that represents a part-whole or part-of relationship. As a type of association, an aggregation can be named and have the same adornments that an association can. However, an aggregation may not involve more than two classes.
In UML it is graphically represented as a hollow diamond shape on the containing class end of the tree with a single line that connects the contained class to the containing class. The aggregate is semantically an extended object that is treated as a unit in many operations, although physically it is made of several lesser objects

class Car {
          Headlight headlight = new Headlight();
           ............
          ...............
}


Composition means strong has-a relationship between object. for example car and engine, if engine is removed then car can not run. That means if both object are tightly associated hence this makes strong relationship between object.In other word Composition usually has a strong life cycle dependency between instances of the container class and instances of the contained class(es): if the container is destroyed, normally every instance that it contains is destroyed as well. (Note that, where allowed, a part can be removed from a composite before the composite is deleted, and thus not be deleted as part of the composite.)
The UML graphical representation of a composition relationship is a filled diamond shape on the containing class end of the tree of lines that connect contained class(es) to the containing class.

class Car {
   Engine engine = new  Engine();
   ...................
   ..................

}

Monday 21 July 2014

How HashMap Works Internally in Java? Internal implementation of HashMap

Java Hashmap uses key/value concepts to store the item. Some basics like -
                       HashMap map = new HashMap();
                       map.put(key, value); /// add the item to map
                       map.get(key);// get the item from map.

In this blog I will tell you how it works internally. So to know internally let see below HashMap API main code (code is not full only required part I am showing here)-

public class HashMap<K,V>    extends AbstractMap<K,V>    implements Map<K,V>, Cloneable, serializable
{
     transient Entry[] table;

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;
…………………
………………….
}
     public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
       if (e.hash==hash&&((k=e.key)==key||key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
 
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }
 
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        int hash = hash(key.hashCode());
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
        if (e.hash == hash && ((k = e.key)==key||key.equals(k)))
                return e.value;
        }
        return null;
    }
}
 
As you can see in above code main is Entry[], get() ,put() And Entry inner class.
Let see one by one how put() method is working here- 

First line of put method() - key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0. Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hashcode value is used to calculate index in array for storing Entry object. This index is nothing but bucket index. That means all the item in HashMap is stored in Bucket. you can see from below diagram, HashMap has Entry[] array i.e array of bucket.


As you have seen hashcode() is required to get the index value of bucket that means if we want to store key as a object in HashMap then key object should always override the hashCode() method.Now
assume we are storing below class as a key in HashMap-

            class Key{
                  int key;
                  Key(int key){
                     this.key = key;
                  }
                  public int hashCode(){
                      return 10;
                  }
            }
 


 So to add as a key in HashMap I will use below code -
                      HashMap map = new HashMap();
                      map.put(new Key(5), “123”); // key object has hascode value 10
                      map.put(new Key(6),”234”); // key object has hashcode value 10

 So, in this case key hashCode() is always returning 10. So now see in put method of HashMap always will return same bucket number. That means all the key will store in same bucket because hashcode is same for all the key. So this type of condition is called HashMap collision.
See below diagram this diagram shows that 3 entry object in bucket number to 0 and 2 entry object in nth bucket.


Now if bucket is same then how item will store in hashMap or how two different objects will be stored in same array location. Here is the trick all the item which has same bucket number will be stored in linked list. See the Entry inner class of HashMaps has an attribute “next”. This attribute always points to next object in chain. So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location. If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current Entry object becomes next node in LinkedList. If next variable is not null, procedure is followed until next is evaluated as null. But what happen if we try to add another value with same key entered before. Logically, it should replace the old value ,but not.
after determining the index position of Entry object, while iterating over LinkedList on calculated index, HashMap calls equals method on key object for each Entry object. All these Entry objects in LinkedList will have similar hash code but equals() method will test for true equality. If key.equals(k) will be true then both keys are treated as same key object. This will cause the replacing of value object inside Entry object only.


Now let see how get method works-


You can see in get method of HashMap also we need hashCode() of key and then hash function which will calculate the bucket number once bucket number is returned HashMap apply same logic which was applicable to put method. i.e hashcode() method + equals() check for same key if key not found then return null.
  
And make a note that if hashCode is same for key Object then performance will be slow because internally it check everytime hashCode() and equals() and maintain LinkedList and to find the item it has to traverse the linkedlist sequentially,  which will downgrade the performance. so, during the code always avoid the HashMap collision case.