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]+" ");
    }
}




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...