Tuesday, 26 June 2018

forEach() vs forEachOrdered() in java 8 stream

forEach() method performs an action for each element of this stream. For parallel stream, this operation does not guarantee to maintain order of the stream.
forEachOrdered() method performs an action for each element of this stream, guaranteeing that each element is processed in encounter order for streams that have a defined encounter order.
take below example:
    String str = "sushil mittal";
    System.out.println("****forEach without using parallel****");
    str.chars().forEach(s -> System.out.print((char) s));
    System.out.println("\n****forEach with using parallel****");

    str.chars().parallel().forEach(s -> System.out.print((char) s));
    System.out.println("\n****forEachOrdered with using parallel****");

    str.chars().parallel().forEachOrdered(s -> System.out.print((char) s));
Output:
****forEach without using parallel****
sushil mittal
****forEach with using parallel****
mihul issltat
****forEachOrdered with using parallel****
sushil mittal

Friday, 15 June 2018

Inheritance vs Composition in java


They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".


In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implemenation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object.

The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class. 

Inheritance Example:
class Fruit {

// Return int number of pieces of peel that // resulted from the peeling activity. public int peel() {
System.out.println("Peeling is appealing."); return 1; } }
class Apple extends Fruit { }
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple(); int pieces = apple.peel(); } }

if we want to change return type to peel() then it will effect to main method also so solution is composition as below:

Composition Example:
class Fruit {

// Return int number of pieces of peel that // resulted from the peeling activity. public int peel() {
System.out.println("Peeling is appealing."); return 1; } }
class Apple {
private Fruit fruit = new Fruit();
public int peel() { return fruit.peel(); } }
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple(); int pieces = apple.peel(); } }

ref: https://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html

Abstraction vs Encapsulation java

Difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

Encapsulation is also called data hiding.

Encapsulation:
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism for wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
● Declare the variables of a class as private.
● Provide public setter and getter methods to modify and view the variables values.

 Abstraction:
Likewise in Object-oriented programming, abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.

Java Default Method



public interface A {
    void print();
    default void display() {
        System.out.println("A");
    }
}

public interface B {
    void print();
    default void display() {
        System.out.println("B");
    }
}

If implement single interface

public class Testing    implements A {

    public static void main(String args[]) {
        Testing obj= new Testing();
        obj.display();
    }

    @Override
    public void print() {
         System.out.println("print");
       
    }

}

If implement multiple interface with same default method

public class Testing    implements A,B {

    public static void main(String args[]) {
        Testing obj= new Testing();
        obj.display();
    }

    @Override
    public void display() {
        B.super.display(); //if we want call A class then A.super.display
    }

    @Override
    public void print() {
         System.out.println("print");
       
    }

}

Lambda Expression Java

A Lambda expression (or function) is just an anonymous function, i.e., a function with no name and without being bounded to an identifier. They are written exactly in the place where it’s needed, typically as a parameter to some other function.

Syntax:

either
(parameters) -> expression
or
(parameters) -> { statements; }
or
() -> expression

Example:

package lambda;


public class Two {
    public static void main(String args[]) {
        new Thread(new Runnable() {
           
            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.out.println("hello runnable");
            }
        }).start();
       
        new Thread(()-> System.out.println("hello lambda runnable")).start();
       
    }
}


Ref: https://howtodoinjava.com/java-8-tutorial/

Sort using lambda exp.


 By using lambda expression we can sort object list using single line of code.

package lambda;

import java.util.ArrayList;
import java.util.List;

public class CompareByName {
    public static void main(String args[]) {
        List<Employee> list = new ArrayList<>();
        list.add(new Employee("sushil",15));
        list.add(new Employee("mittal",25));
        list.add(new Employee("kumar",20));
       
        System.out.println("***********original list*****");
        list.forEach(e-> System.out.println(e));
        System.out.println("***********sort by name******");
        list.sort((e1,e2)-> e1.getName().compareTo(e2.getName()));
        list.forEach(e-> System.out.println(e));
        System.out.println("***********sort by age******");
        list.sort((e1,e2)-> e1.getAge()- e2.getAge());
        list.forEach(e-> System.out.println(e));
    }
   
     static class Employee{
        String name;
        Integer age;
       
        public Employee(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

       
        public String getName() {
            return name;
        }

       
        public void setName(String name) {
            this.name = name;
        }

       
        public Integer getAge() {
            return age;
        }

       
        public void setAge(Integer age) {
            this.age = age;
        }


        @Override
        public String toString() {
            return "Employee [name=" + name + ", age=" + age + "]";
        }
       
    }
   
}


output:
 ***********original list*****
Employee [name=sushil, age=15]
Employee [name=mittal, age=25]
Employee [name=kumar, age=20]
***********sort by name******
Employee [name=kumar, age=20]
Employee [name=mittal, age=25]
Employee [name=sushil, age=15]
***********sort by age******
Employee [name=sushil, age=15]
Employee [name=kumar, age=20]
Employee [name=mittal, age=25]



Friday, 8 June 2018

Find Minimum Length Sub Array With Sum K

public class FindMinimumLengthSubArrayWithSumK {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arr = {2,3,1,1,-1,6,4,2,1,8};
        int val = 7;
        findLength(arr, val);
    }
   
   
    public static void findLength(int[] arr, int val) {
        int start=0;
        int end=0;
        int finalCount = arr.length;
        for(int i=0;i<arr.length;i++) {
            int sum = 0;
            int count = 0;
            for(int j=i;j<arr.length;j++) {
                sum+= arr[j];
                count++;
                if(sum==val && count<finalCount) {
                    start = i;
                    end = j;
                    finalCount = count;
                    break;
                }
            }
        }
       
        System.out.println("start::"+start);
        System.out.println("end::"+end);
        System.out.println("final count::"+finalCount);
    }

}

output::
start::6
end::8
final count::3

How to deploy a war file to remote server on tomcat using shell script


Step1: reach to project directory where pom.xml file exist from terminal
Step2: clean mavan using below
mvn clean
Step3: create a war file
mvn package
Step4: remove existing war from webapps tomcat
ssh user@address 'rm /data/apache-tomcat-8.0.29/webapps/warFile'
Step5: remove module exist in webapps tomcat
ssh user@address 'rm -rf moduleName'
Step6: copy war file to wenapps tomcat to remote server
scp /pathOf local dirctory/project.war user@address:/data/apache-tomcat-8.0.29/webapps
echo "deployment done"!

we need to provide some write permission to remote server webapps folder using below:
step1: need to login remote server in teminal
step2: move to directory where you want to provide write access
step3:   chmod -R 777 .

we also need to add our system public key to remote because it will not ask password during deployment:
cat ~/.ssh/id_rsa.pub | ssh user@address 'cat >> .ssh/authorized_keys'


complete script save into a file(deploywar.sh):
mvn clean
mvn package
ssh user@address 'rm /data/apache-tomcat-8.0.29/webapps/warFile' 
ssh user@address 'rm -rf moduleName' 
scp /pathOf local dirctory/project.war user@address:/data/apache-tomcat-8.0.29/webapps 
echo "deployment done"! 

 execute below command from terminal from project location where pom.xml file exist:
/path where script file /deploywar.sh
 

Thursday, 7 June 2018

Find an element in a sorted rotated array


public class FindElementInSortedRotatedArray {

    public static void main(String[] args) {
        int findValue = 98;
        int[] arr = {25,35,45,65,67,78,97,98,2,3,4,7,11,22,23,24};
            boolean bool = checkArrIsRotated(arr);
             if(bool) {
                 int index = findPivot(arr);
                 if(findValue>=arr[0] && findValue<=arr[index]) {
                     //first half
                System.out.println(binarySearch(arr, 0, index, findValue));
                 }else {
                     //second half
                System.out.println(binarySearch(arr, index+1, arr.length-1, findValue));
                 }
             }else {
                 //no rotated arr
                 System.out.println(binarySearch(arr, 0, arr.length-1, findValue));
             }
    }
   
    public static int binarySearch(int[] arr,int start,int end,int findValue) {
       
        int mid = 0;
        while(start<=end) {
            mid = (start+end)/2;
            if(arr[mid]==findValue) {
                return mid;
            }else if(findValue<arr[mid]) {
                end = mid-1;
            }else {
                start = mid+1;
            }
        }
        return -1;
    }
   
    public static int findPivot(int[] arr) {
        int start = 0;
        int end = arr.length-1;
        int mid = 0;
        while(start<=end) {
            mid = (start+end)/2;
            if(arr[mid]>arr[mid+1]) {
                return mid;
            }else if(arr[start]<arr[mid]) {
                start = mid+1;
            }else if(arr[start]>arr[mid]) {
                end = mid-1;
            }
        }
        return -1;
    }
   
    public static boolean checkArrIsRotated(int[] arr){
        if(arr[0]>arr[arr.length-1]) {
            return true;
        }
        return false;
       
    }
}

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...