Saturday, 8 September 2018

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface.

As per java doc, "Lamda Expression enables Functional Interface" that means Lamda Expression allows us to write Functional Programming.

Please note that Lamda Expression takes or accepts only those interfaces which are having only one abstract method.

So What is Functional Interface?

A functional interface is an interface which is having only one abstract method. For example, we can consider as

  • java.util.Comparator interface
  • Java.lang.Runnable interface
We have created one customize Functional Interface MathHelper which is having only one method as sum(int val1, int val2).



Please note, annotation @FunctionalInterface is used to tell us that this interface will be used as Functional Interface.

Now what will happen if we add one more method multiply(int val1, int val2) like below,






Well, above scenario will not work here, compiler will give us an error as Functional Interface can not contain more that one abstract method. To overcome this problem, we can have a number of default methods like below:












What is Lamda Expression?

We are familiar with Functional Interface now but question is how can we use this functional interface in our code.

Well, the answer is Lamda Expression. Lamda expression is introduced in Java 8 and it is an Instance of Functional Interface.

Let us think that if Lamda Expression would not have introduced, then how can we implement the MathHelper Interface in Java 7. So we need to have One class lets say MathHelperImpl which implements MathHelper interface like below.














So does not it look like little lengthy because just to achieve the sum() function, we have to implement the Interface and have to Instantiate the class.

But question is why do we need to create the object? Can't we do this as a function without implementing or creating a new Object.

We can write a block of code to a variable and where ever this variable goes, this block of code also goes with that. Lets see below example,

String country= "India" // here india is assigned to a variable called country.

Double piVal="3.14" // here 3.14 is assigned to a variable called piVal.

As per above example, where ever we will use country, piVal variables in our code its value also passes with it.

If we can write a block of function like below where entire function is assigned to a variable then we can solve the above problem.

lamdaVal={
         .................. our functional code comes here............
         ..........................
                   }
So let us write the sum() method like below:
lamdaVal=public int sum(int val1, int val2) {
        return val1 +val2;}
    }

But we can get rid of couple of things from the above block like:
public - This is really not required while writing a block of code because we are writing this block inside some class or method only.
int- We don't need to mention return type as compiler can understand the return type by seeing the functional interface.
sum - For a block of code, we don't need to mention any name just like anonymous method. 

So finally the above block will look like:

lamdaVal=(int val1, int val2) {
        return val1 +val2;
    }
Even we can more specify it as below
lamdaVal=(val1, val2) {
        return val1 +val2;
    }
So the syntax is pretty much same for the Lamda Expression except one addition which is:
lamdaVal=(val1, val2) -> { val1 +val2 ;
    }
If we have only one line of code in that case we can re write the above the code as 
lamdaVal=(val1, val2) -> val1 +val2 ;

So finally we can re write our above Java 7 code using Lamda Expression in Java 8 as below:



    







Complete Example of Lamda && Functional Interface:





















Couple of things we can see from the above Lamda code...

1. We don't implement the MathHelper Interface here rather than we are using it as a functional way.

2. Using Lamda Expression we can write very less code which can not be done in Java 7.

That's all for Java 8 Functional Interface and Lamda Expression. I keep it as simple as I can. Hope you like it. I would love to see your comment and feedback.



Sunday, 18 February 2018

Java Program to check a String contains all alphabet or not.

This question can be asked in different ways like " tell if a String contains a-z character or not" and "How can we check a String contains only Alphabet".

To solve a String contains all the alphabet or not, we will take set. We will Iterate the String and every time we will add the iterated character into the Set.

If the set size is 26 that means the String contains all the alphabet.

Here is the code snippet:

public class AllAlphabetInString {

public static void main(String[] args) {
int noOfAlphabet=26;
String text="We promptly judged antique ivory buckles for the next prize";
Set<String> alphaSet=new HashSet<>();

//uses regular expression to filter out special character from the String..
Pattern pattern=Pattern.compile("[A-Za-z]");
Matcher matcher=pattern.matcher(text);
boolean findAll=false;

while(matcher.find()&&!findAll)
{
String s=matcher.group().toLowerCase();
alphaSet.add(s);
if(alphaSet.size()==noOfAlphabet)
{
findAll=true;
}
}
System.out.println("Result: "+findAll);
}
}

How to remove Duplicate elements from a Sorted Array

This is another popular coding interview question. I had faced this question during my interview with Reliance Jio.

You are given a sorted array like { 2,2,2,2}, so the final array would be {2}.

Examples: 

Input:       arr[]={5,5,5,5}
Output:    arr[]={5}

Input:       arr[]={1, 2, 2, 3, 4, 4, 4, 5, 5}
Output:    arr[]={1,2,3,4,5}

Logic: To solve this problem, we will take another variable as j. Every time we will check i th element with i+1 th element. If it does not match, will increase j with j+1.

Program:

public class DuplicateArrayElement {
static int removeDuplicates(int arr[], int n)
    {
        if (n == 0 || n == 1)
            return n;
        
        //Taking extra index which will be increased based on iTh and i+1 Th index
        int j = 0;
      
        for (int i = 0; i < n-1; i++)
            if (arr[i] != arr[i+1])
                arr[j++] = arr[i];
      
        arr[j++] = arr[n-1];
      
        return j;
    }

//** Main method to test the method removeDuplicates()**//

    public static void main (String[] args) 
    {
        int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
        int n = arr.length;
         
        n = removeDuplicates(arr, n);
  
        for (int i=0; i<n; i++)
           System.out.print(arr[i]+" ");
    }
}




Thursday, 25 January 2018

How to create or design your own HashMap in JAVA

One of my friends had recently faced this question during his interview with JP Morgan. You can expect this kind of questions in every product based company.

To design our own HashMap, we should know how java.util.HashMap internally works. HashMap has DEFAULT_SIZE of 16 that means DEFAULT capacity of HashMap is 16 buckets and load factor is 0.75.

Internally HashMap has Entry class, which contains Key and Value.

Every time when we put some value into the HashMap, internally it will calculate the hashCode() of the given key to find out the correct bucketId to place that object inside that index.

Every time when we get() some value based on key, it will calculate the hashCode of that key and go to the correct basketId and returns the  object.

Here is the implementation of Entry class:

package design.own.hashmap;

public class Entry<K,V> {

K key;
V value;
Entry<K,V> next;
public Entry(K key, V value)
{
this.key=key;
this.value=value;
next=null;
}

public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public Entry<K, V> getNext() {
return next;
}
public void setNext(Entry<K, V> next) {
this.next = next;
}
}

**********Implementation of complete HashMap***********

package design.own.hashmap;

public class HashMap<K,V> {

private int DEFAULT_SIZE=16;
private Entry<K,V>[] entryBucket;
public HashMap(){
entryBucket=new Entry[DEFAULT_SIZE];
}
public HashMap(int capacity){
entryBucket=new Entry[capacity];
}
public void put(K key, V value)
{
int bucketIndex=getBucketindex(key);
Entry<K,V> entry=entryBucket[bucketIndex];
if(entry!=null){
boolean done=false;
while(!done)
if(key.equals(entry.getKey())){
entry.setValue(value);
done=true;
}else if(entry.getNext()==null)
{
entry.setNext(new Entry<K,V>(key, value));
}
entry=entry.getNext();

}else{
entryBucket[bucketIndex]=new Entry<K,V>(key, value);
}
}
/**
* this method returns the basketId based on applying hashCode on given key
* @param key
* @return
*/
public int getBucketindex(K key)
{
int val=key.hashCode()%10;
return val;
}
public V get(K key) {
Entry<K, V> entry = entryBucket[getBucketindex(key)];
while (entry != null && !key.equals(entry.getKey()))
entry = entry.getNext();
return entry != null ? entry.getValue() : null;
}

}


**************************Test Class************************

package design.own.hashmap;

public class HashMapTest {

public static void main(String[] args) {
HashMap<Integer,Integer> map=new HashMap<>();
map.put(1,10);
map.put(2,20);
map.put(11,30);
System.out.println("Val is: "+ map.get(1));
}

}


*****************End of Custome HashMap Implementation***************

So as per our above implementation, when we put key as 1, it will calculate its hashCode and return bucketIndex as 1 so 10 will be kept inside 1 bucketIndex.

Next time we put 2 as key, so it will calculate its bucket index and put 20 inside 2 bucketIndex.

Now we put 11 as key and its bucket index is 1, but 10 is already there inside bucketIndex 1, so this time it will create one more Entry node which will be next to node 10.

Please see the below Image, we assumed we have 16 buckets and based on our above main class, it will be like:

You may also like:

Singleton Design pattern, a complete guide
Determine if a String has all unique character or not in JAVA
Converting String to Integer without using any Standard Library in JAVA







Saturday, 9 December 2017

Singleton Design Pattern, a complete guide

In this blog, we are going to discuss all about Singleton Design Pattern which is one of the popular topic during Java Interview.

You can see a lot of discussion on this topic on various  blogs or sites in google but what I personally feel none of them have covered the entire design. So here I am going to share the complete design step by step.

What is Singleton pattern?

Singleton pattern ensures that class has only one instance and it provides a global point to access it.
Real time example of Singleton pattern is JDBC  getConnection() method.
Below one is the sample implementation of Singleton class:

public class SingleTon {
private static SingleTon singletonObj;
//constructor should be always private ,else somebody can easily     //creates its object.
private SingleTon()
{

}
public static SingleTon getInstance()
{
if(singletonObj==null)
singletonObj=new SingleTon();

return singletonObj;

}

}


/****End of code****/


So here we have created the Singleton class which restricts creation object using new operator as we made the constructor as private. So we have ensured that at any point time there would be only one instance of Singleton Class. We can write the code in main() method as below:

public static void main(String args[]){
  SingleTon singleton=SingleTon.getInstance();
}

Congratulation!!! We have created the SingleTon instance which can be accessed globally.

Wait!!!!!, this code can be cracked using Reflection in java that means even though we made Constructor as private but still during run time any body can create its instance using Reflection, here is the code snippet.

public class SingleTontest {

public static void main(String[] args) throws                               InstantiationException, IllegalAccessException,                     IllegalArgumentException, InvocationTargetException {

 /**
  * getDeclaredConstructors() method returns the number of            *   constructor present in the class,
  * default constructor always comes in 0th index 
  */
Constructor[] cons =                                                 SingleTon.class.getDeclaredConstructors();
cons [0].setAccessible(true); 

// get the instance of the class, initially it was                   // null,


SingleTon s2=(SingleTon)cons[0].newInstance();


System.out.println("hashcode after creating new                             Intance--> "+s2.getInstance().hashCode());


// get all the declared fields, in our class we                     // have only one declared field as singletonObj


Field [] f1=s2.getClass().getDeclaredFields();


f1[0].setAccessible(true);


//setting the singletonObj as NULL during runtime                   //using Reflection


f1[0].set(f1[0].getName(), null);


System.out.println("after setting null to                             singletonObj--> "+s2.getInstance().hashCode()); 


   }


}


Output:

hashcode after creating new Intance--> 366712642

after setting null to singletonObj--> 1311053135


So here we can conclude that using reflection we can create a new instance even though contructor is private and we can change its state to null as well.


So the Question here is how we can come out of this problem. Here is the solution, we have to throw UnsupportedOperationException() from the constructor which can ensure if anybody try to create an instance, it will throw this exception.

Code Snippet:

public class SingleTon {
private static SingleTon singletonObj;
//constructor should be always private, else somebody can //easily creates its object.

private SingleTon()
{
     throw new UnsupportedOperationException();
}

public static  SingleTon getInstance()
{
if(singletonObj==null)
singletonObj=new SingleTon();

return singletonObj;

}


}


But We are not yet done!!, what will happen if multiple threads like Thread 1, Thread 2, Thread 3 will try access getInstance() method, will it creates three different singletonObj for three threads, well quite possible as per our above class design.

To resolve this issue, we should use synchronized keyword to make the getInstance method as Thread safe which ensures, at a time only one thread will be executed.

Lets imagine the scenario like Thread 1 access the getInstance() method so Thread 2 and Thread 3 will have to wait unless Thread 1 come out of getInstance() method. Next time when Thread2 or Thread 3 will access the getInstance() method, it will see that singleton instance has already been created so they wont create any other singleTon object. 

Well but it will impact the performance because every thread has to wait at the method level, to resolve this issue, we can synchronized only the condition where it check the instance value, which can improve the performance.

Here is the complete Singleton class:

public class SingleTon {
private static SingleTon singletonObj;
//constructor should be always private ,else                //somebody can easily creates its object.
private SingleTon()
{
throw new UnsupportedOperationException();
}
public static  SingleTon getInstance()
{

if(singletonObj==null)
synchronized (SingleTon.class) {
if(singletonObj==null)
singletonObj=new                                                    SingleTon();
}

return singletonObj;

}

}


/***************End of SingleTon design pattern**************/


You may also Like:

Design your custom or own HashMap implementation in JAVA







Saturday, 9 September 2017

Determine if a String has all unique character or not in JAVA

We can determine a String has all unique characters or not by several ways.
Suppose you are given a String like "abcdef10&g" and our program should return TRUE as it contains all unique characters, but for a String like "abccdefg", the output would be FALSE.

I am going to use a boolean array to solve this approach. Initially each element of the array would be FALSE. We will find out the ASCII value of each character and check the current value for that index in boolean array, if the value is FALSE that means the character is unique and make the value TRUE.

If the value is TRUE that means character is already present and the String contains non-unique characters.

Sample Code:

/**
 * 
 * @author Sourin M
 *
 */
public class UniqueString {
public static void main(String[] args) {
String uniqueTest="abcdef10gg";
if(isUniqueChanracter(uniqueTest))
System.out.println("Yes, Unique String.");
else
System.out.println("No, its not unique ");
}

private static boolean isUniqueChanracter(String uniqueTest) {

boolean unique_set[]=new boolean[256];
for(int i=0;i<uniqueTest.length();i++)
{
int val=uniqueTest.charAt(i);
if(unique_set[val])
return false;
else
unique_set[val]=true;
}
return true;
}

Friday, 8 September 2017

Converting String to Integer without using any Standard Library in JAVA

This question can be asked in both service and product based company as well.
Suppose you are given a String like "12345" and after converting it should be "12345".
Normally using standard library we can convert this using Integer.parseInt("") or Integer.valueOf("").

Without using standard library, we will find out ASCII code of each character and subtract it with '0' which will give current int value and finally multiply by 10 to get actual result.

Initially we will check it starts with negative or not, if negative then substract the result from 0 at last else do nothing.

Input: "12345"
Output: 12345

Input: "-12345"
Output: -12345

Sample Code:

/**
 * 
 * @author Sourin M
 *
 */
public class StringToInteger {

public static void main(String[] args) {

String number="-1234567";
System.out.println("Number is: "+ getNumber(number));

}
public static int getNumber(String number) {
   int result = 0;
   boolean isNegative=false;
   if(number.charAt(0)=='-')
   {
    isNegative=true;    
   }else
   {
    result=number.charAt(0)-'0';
   }
   for (int i = 1; i < number.length(); i++) {
    result = result * 10 + number.charAt(i) - '0';
   }
   if(isNegative)
    result=0-result;
   return result;

}



}

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...