Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, 3 September 2021

install java in ubuntu

 #Login as root

sudo su

#create jdk directory
mkdir /opt/jdk

#uncompress, change to your file name
tar -zxf jdk-8u5-linux-x64.tar.gz -C /opt/jdk

#check if files are there
#ls /opt/jdk

#update alternatives so the command java point to the new jdk 
update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_05/bin/java 100


#update alternatives so the command javac point to the new jdk 
update-alternatives --install /usr/bin/javac javac /opt/jdk/jdk1.8.0_05/bin/javac 100

#check if java command is pointing to " link currently points to /opt/jdk/jdk1.8.0_05/bin/java"
update-alternatives --display java

#check if java command is pointing to " link currently points to /opt/jdk/jdk1.8.0_05/bin/javac"
update-alternatives --display javac

#check if java is running
java -version


sudo  update-alternatives --config java

Sunday, 2 May 2021

Group Shifted Strings

 


import java.util.*;


//https://www.youtube.com/watch?v=uEXJSRLqoKY&t=54s

public class GroupShiftedStrings {

    public static void main(String[] args) {

        String arr[] = {"abc","bcd","acef","xyz","az","ba","a","z","pqr","ace","jln"};

        List<List<String>> result = groupStrings(arr);

        System.out.println(result);

    }


    private static List<List<String>> groupStrings(String[] arr) {

        Map<String, List<String>> map = new HashMap<>();


        for(int i = 0;i<arr.length;i++){

            char[] charArr = arr[i].toCharArray();

            String key = "";

            if(charArr.length==1){

               key = "#";

            }else{

                for(int j=1; j<charArr.length;j++){

                    int diff  = (int)(charArr[j]-charArr[j-1]);

                    if(diff<0){

                        diff = diff+26;

                    }

                    key  = key + diff+"#";

                }

            }

            List<String> list = null;

            if(map.containsKey(key)){

               list = map.get(key);

            }else{

                list = new ArrayList<>();

            }

            list.add(arr[i]);

            map.put(key,list);


        }


        System.out.println(map);

        List< List<String>> result = new ArrayList<>();

        map.forEach((k,v)-> Collections.sort(v));


        result.addAll(map.values());


        return result;

    }

}



output:

{25#=[az, ba], 1#1#=[abc, bcd, xyz, pqr], 2#2#1#=[acef], #=[a, z], 2#2#=[ace, jln]}

[[az, ba], [abc, bcd, pqr, xyz], [acef], [a, z], [ace, jln]]

Friday, 29 January 2021

Method overriding rule important

 1. return type can be different  ,  if they return a subtype like parent class return type Number and child class Integer.

2.Another worth noting rule of method overriding in Java is that the overriding  method can not throw checked Exception which is higher in the hierarchy than the overridden method. This means if the overridden method throws IOException than the overriding method can not throw java.lang.Exception in its throws clause because of java.lang.Exception comes higher than IOException in Exception hierarchy. 

3. You can not override private, static and final the method in Java. private and static method are bonded during compile time using static binding in Java and doesn't resolve during runtime. the overriding the final method in Java is a compile-time error. Though private and static methods can be hidden if you declare another method with the same and signature in the subclass.

4.to override a method in Java is that the overriding method can not reduce the accessibility of the overridden method in Java. For example, if the overridden method is public than the overriding method can not be protected, private or package-private

Tuesday, 8 December 2020

Multi threading example - synchonized ,static

public class Test {

    public static void main(String[] args) {

        sample obj = new sample();


        t1 tt1 = new t1(obj);

        t2 tt2 = new t2(obj);

        tt1.start();

        tt2.start();

    }

}

//It’s possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.

class sample{

    public synchronized static void m1(String name){

        System.out.println(name+":m1");

        try {

            Thread.sleep(2000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

    public synchronized void m2(String name){

        System.out.println(name+":m2");

        try {

            Thread.sleep(2000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}


class t1 extends  Thread{

    sample s;

    t1(sample s){

        this.s =s;

    }

    @Override

    public void run() {

        s.m1(Thread.currentThread().getName());

        s.m2(Thread.currentThread().getName());

    }

}


class t2 extends Thread{

    sample s;

    t2(sample s){

        this.s =s;

    }

    @Override

    public void run() {

        s.m2(Thread.currentThread().getName());

        s.m1(Thread.currentThread().getName());


    }

}

output: 

Thread-1:m2

Thread-0:m1

wait 2 second

Thread-0:m2

Thread-1:m1 


or

Thread-0:m1

Thread-1:m2

wait 2 second

Thread-0:m2

Thread-1:m1

Thursday, 9 July 2020

Arranging Coins : LeetCode

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the 4th row is incomplete, we return 3.
Solution:
class Solution {
    public int arrangeCoins(int n) {
        long start =0;
        long end = n;
        while(start<=end){
            long k = start+(end-start)/2;
            long total = k*(k+1)/2;
            if(total==n){
                return (int)k;
            }
            if(n<total){
                end = k-1;
            }else{
                start = k+1;
            }
        }
        return (int)end;
    }
}

Plus One : LeetCode

Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Solution:
class Solution {
    public int[] plusOne(int[] digits) {
       int length = digits.length;
        int i=length -1;
        while(i>=0){
            if(digits[i]!=9){
                digits[i] = digits[i]+1;
                return digits;
            }
             digits[i]=0;
            i--;
            
        }
        int[] finalArr = new int[length+1];
        finalArr[0]=1;
        return finalArr;
    }
}

Monday, 25 November 2019

Generic function for Post Data with some headers in spring

 public <T,K> K postApiCall(T t, HttpHeaders headers, String url, Class<K> resposne){
        try {
            RestTemplate restTemplate = new RestTemplate();
            headers.add("Content-Type","application/json");
            HttpEntity<T> entity = new HttpEntity<T>(t, headers);
            ResponseEntity<K> result = restTemplate.exchange(url, HttpMethod.POST, entity, resposne);
            System.out.println(result.getBody());
            return result.getBody();
        }catch (Exception ee){
            ee.printStackTrace();
        }
        return null;
    }

Thursday, 20 June 2019

Send Multipart file in resttemplate Java Spring

import java.io.File;
import java.io.IOException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
public class Application {
public static void main(String[] args) throws IOException {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
FileSystemResource value = new FileSystemResource(new File("D://test.png"));
map.add("file", value);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange("http://localhost/api/v1/users/avatar", HttpMethod.POST, requestEntity, String.class);
}
}

ref: https://gist.github.com/ansidev/5816b8b3108c30b5279f5fec67506798

Saturday, 9 February 2019

Delete a node from BST


public class DeleteFromBST {
    public static void main(String[] args) {
        int[] arr = {5,3,8,2,1,6,7,4,9};
         Node root = null;
         for(int val:arr) {
             root =  insertNode(root, val);
         }
         Node node= removeNode(root, 5);
         printInorder(node);
    }
   
    static Node removeNode(Node root, int key) {
        if(null!=root) {
            if(key<root.value) {
                root.left = removeNode(root.left, key); //if key small then current node then recursion for left
            }else if(key>root.value) {
                root.right = removeNode(root.right, key);//if key small then current node then recursion for right
            }else {
                //check how many nodes after found current node
               
                //if only one child at key node or no child
                if(root.left==null) {
                    return root.right;   
                }else if(root.right==null) {
                    return root.left;
                }
               
                //if 2 child at key node
                //pass right
                root.value = findMin(root.right);//replace key node with min node
                root.right = removeNode(root.right, root.value);//remove duplicate min node from right as in previous step we hvae find min node from right
            }
           
        }
        return root;
    }
   
    static int findMin(Node node) {
        //find min till all left node end due to inorder successor rule
        int min = node.value;
        while(null!=node.left) {
            if(min>node.left.value) {
                min = node.left.value;
                node = node.left;
            }
        }
       
        return min;
    }
   
   
    static void printInorder(Node node) {
        if(null!=node) {
            printInorder(node.left);
            System.out.println(node.value);
            printInorder(node.right);
        }
    }
   
    static Node insertNode(Node root, Integer value) {
        Node newNode = new Node(value);
        if (root == null) {
            return newNode;
        } else {
            if (value <= root.value) {
                root.left = insertNode(root.left, value);
            } else {
                root.right = insertNode(root.right, value);
            }
            return root;
        }

    }
    static class Node{
        Integer value;
        Node left;
        Node right;
        Node(Integer value){
            this.value = value;
            left = right = null;
        }
    }
}

ref: https://www.geeksforgeeks.org/binary-search-tree-set-2-delete/

Saturday, 29 December 2018

Implement ThreadPool in java

public class Test {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(2);
        for(int i=0;i<2;i++) {
            Task task = new Task(i);
            threadPool.execute(task);
        }
        System.out.println("done");
    }
}


public class Task implements Runnable{

    int i;
   
    public Task(int i) {
        this.i = i;
    }
   
    @Override
    public void run() {
   
         System.out.println("executing i::"+i);
       
    }

}


public class ThreadPool {
    int nThread;
    private LinkedBlockingQueue<Runnable> queue;
    PoolWorker[] arr ;
   
    public ThreadPool(int nThread) {
        this.nThread = nThread;
        this.queue = new LinkedBlockingQueue<>();
        arr = new PoolWorker[nThread];
        for(int i=0;i<nThread;i++) {
            PoolWorker poolWorker = new PoolWorker();
            arr[i] = poolWorker;
            arr[i].start();
        }
    }
   
    public void execute(Task task) {
        synchronized (queue) {
            queue.add(task);
            queue.notify();
        }
       
    }
   
    class PoolWorker extends Thread{

        @Override
        public void run() {
             Runnable task;
             while(true) {
                synchronized (queue) {
                    while(queue.isEmpty()) {
                         try {
                            queue.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                     }
                     task = queue.poll();
                }
               
                task.run();
             }
           
           
           
        }
       
    }
   
}

Ref: https://www.javacodegeeks.com/2016/12/implement-thread-pool-java.html

Saturday, 22 September 2018

Algorithm for finding the maximum element in binary tree without recursion java

public void findMax(Node node) {
        int root_val,max_val=0;
        if(null!=node) {
              Queue<Node> queue = new LinkedBlockingQueue<>();
              queue.add(node);
             
              while(!queue.isEmpty()) {
                  Node temp = queue.remove();
                  root_val = temp.value;
                  max_val = max_val<root_val ? root_val :max_val;
                 
                  if(null!=temp.left) {
                      queue.add(temp.left);
                  }
                  if(null!=temp.right) {
                      queue.add(temp.right);
                  }
              }
             
        }
       
        System.out.println(max_val);
    }

Algorithm for searching an element in binary tree java

public class SearchANodeUsingRecusrtion {
    public static void main(String args[]) {
        Node node = new Node(1);
        node.left = new Node(2);
        node.right = new Node(3);
        node.left.left = new Node(4);
        node.left.right = new Node(5);
        node.right.left = new Node(6);
        node.right.right = new Node(7);
        SearchANodeUsingRecusrtion searchANodeUsingRecusrtion = new SearchANodeUsingRecusrtion();
        int output = searchANodeUsingRecusrtion.searchNode(node,6);
        if(output==1)
            System.out.println("found");
        else
            System.out.println("not found");
    }
   
    public int searchNode(Node node,int key) {
        if(null!=node) {
            if(node.value==key) {
                return 1;
            }else {
                int temp = searchNode(node.left,key);
                if(temp!=0) {
                    return 1;
                }else {
                 temp =    searchNode(node.right,key);
                 return temp;
                }
               
            }
       
        }else {
            return 0;
        }
       
    }
   
}


class BinayTree{
    static class Node{
        String value;
        Node left;
        Node right;
       
        Node(String val){
            value = val;
            left = right = null;
        }
       
    }
   
}

algorithm for searching an element in binary tree without recursion java

public class SearchNodewithoutRecursion {
    public static void main(String args[]) {
        Node node = new Node(1);
        node.left = new Node(2);
        node.right = new Node(3);
        node.left.left = new Node(4);
        node.left.right = new Node(5);
        node.right.left = new Node(6);
        node.right.right = new Node(7);
        SearchNodewithoutRecursion searchANodeUsingRecusrsion = new SearchNodewithoutRecursion();
        int val = searchANodeUsingRecusrsion.findNode(node, 4);
        if(val==1)
            System.out.println("found");
        else
            System.out.println("not found");
    }
   
    public int findNode(Node node, int key) {
        if(null!=node) {
            Queue<Node> queue = new LinkedBlockingQueue<>();
            queue.add(node);
            while(!queue.isEmpty()) {
                Node temp = queue.remove();
                System.out.println(temp.value);
                if(temp.value == key) {
                    return 1;
                }
                if(null!=temp.left) {
                    queue.add(temp.left);
                }
                if(null!=temp.right) {
                    queue.add(temp.right);
                }
            }
        }
            return 0;
       
    }
}

class BinayTree{
    static class Node{
        String value;
        Node left;
        Node right;
       
        Node(String val){
            value = val;
            left = right = null;
        }
       
    }
   
}

Sunday, 19 August 2018

find max sub array program

Program1: find sum of maxSubArray

 public int maxSubArray(final int[] A) {
     int largestSum = Integer.MIN_VALUE;
        int tempSum = 0;
        for(int i=0;i<A.length;i++) {
            if(tempSum+A[i]<A[i]) {
                tempSum = A[i];
            }else {
                tempSum = tempSum+A[i];
            }
           
            if((tempSum>Integer.MIN_VALUE && tempSum>largestSum) || tempSum>0) {
                 if(largestSum<tempSum){
                    largestSum = tempSum;
                
                    }
            }else {
                tempSum=0;
            }
        }
        return largestSum;
    }


intput:{-2,1,-3,-4,-1,-2,-1,-7,-5,-4}

output: 1


innput:{-160,-20,-10}
output -10

input: -160,-20,-10,1,2
output: 3



Program2: find sum of maxSubArray with start and end index

public static void findMaxSumSubArray(int[] arr) {
        int largestSum = Integer.MIN_VALUE;
        int tempSum = 0;
        int startIndex = 0;
        int endIndex = 0;
        int s = 0;
        for(int i=0;i<arr.length;i++) {
            if(tempSum+arr[i]<arr[i]) {
                tempSum = arr[i];
            }else {
                tempSum = tempSum+arr[i];
            }
           
            if((tempSum>Integer.MIN_VALUE && tempSum>largestSum) || tempSum>0) {
                 if(largestSum<tempSum){
                     endIndex = i;
                     startIndex = s;
                    largestSum = tempSum;
               
                    }
            }else {
                s = i+1;
                tempSum=0;
            }
        }
        System.out.println("index start::"+startIndex +" and end: "+endIndex);
        System.out.println("sum::"+largestSum);
    }


Sunday, 12 August 2018

TryWithResource java

public class TryWithResource {

        public static void main(String[] args) throws Exception {
            try {
                tryWithResourceException();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            try {
                normalTryException();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        private static void normalTryException() throws Exception {
            MyResource mr = null;
            try {
                mr = new MyResource();
                System.out.println("MyResource created in try block");
                if (true)
                    throw new Exception("Exception in try");
            } finally {
                if (mr != null)
                    mr.close();
               
            }

        }

        private static void tryWithResourceException() throws Exception {
            try (MyResource mr = new MyResource()) {
                System.out.println("MyResource created in try-with-resources");
                if (true)
                    throw new Exception("Exception in try");
            }
        }

        static class MyResource implements AutoCloseable {

            @Override
            public void close() throws Exception {
                System.out.println("Closing MyResource");
                throw new Exception("Exception in Closing");
            }

        }
}
output;


MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in try block
Closing MyResource
Exception in Closing

how its work:
tryWithResourceException called
print: MyResource created in try-with-resources
 before throw exception autoclose will call then print Closing MyResource and throw Exception in closing but its override by Exception in try


normalTryException called
print: MyResource created in try block and throw exception Exception in try but its overrride by finally



Saturday, 11 August 2018

MergeSort Program

Merge Sort:

public class MergeSort2 {

    public static void main(String args[]) {
        int[] arr = {1,12,3,8,2,1,7,9};
        mergeSort(arr, 0, arr.length-1);
        System.out.println(Arrays.toString(arr));
    }
   
    public static void mergeSort(int[] arr, int start, int end) {
        if(start<end) {                               //check start < mid then find mid and divide arr in parts 
            int mid = (start + end)/2 ;
            mergeSort(arr, start, mid);
            mergeSort(arr, mid+1, end);
            merge(arr, start, mid, end); //merge
        }
    }
   
    public static void merge(int[] arr, int start, int mid, int end) {
        int p = start ;
        int q = mid+1;
       
        int[] localArr = new int[end-start+1];
        int k = 0;
        for(int i=start;i<=end;i++) {
            if(p>mid) {
                localArr[k] = arr[q];
                k++;
                q++;
            }else if(q>end) {
                localArr[k] = arr[p];
                k++;
                p++;
            }else if(arr[p]<arr[q]) {
                localArr[k] = arr[p];
                p++;
                k++;
            }else {
                localArr[k]  =arr[q];
                q++;
                k++;
            }
        }
       
        for(int i=0;i<localArr.length;i++) {
            arr[start]  = localArr[i];
            start++;
        }
       
       
    }
   
}

How merge method work:
take an example below
[1,12 ,3,8 ||||||| ,2,1,7,9] start = 0,mid = 1,end = 3
we want to merge 0 to 3

p = 0
q=  mid+1 = 2;
take localarr of size end-start+1 = 4
k=0
loop---> start to < = end
if p reaches to mid then only right part need to insert localarr
if(p>mid) {
                localArr[k] = arr[q];
                k++;
                q++;
            }
if q reaches to end then only left part need to insert into localarr
else if(q>end) {
                localArr[k] = arr[p];
                k++;
                p++;
            }

if arr[p] <arr[q] it means need to insert p position element to localarr and increemt p

else if(arr[p]<arr[q]) {
                localArr[k] = arr[p];
                p++;
                k++;
            }

if arr[p]>arr[q] it means need to insert q position element to localarr and increment q
 else {
                localArr[k]  =arr[q];
                q++;
                k++;
            }

loop exit

now need to insert localarr to original array
  for(int i=0;i<localArr.length;i++) {
            arr[start]  = localArr[i];
            start++;
        }

QuickSort Program

QuickSort:

[5,9,3,15,13,7,1,8,18,14,4]

Steps:

we will choose first element as pivot
move all less than pivot on one side and other on one side

so we need to find the pivot element position
then partition in 2 parts first is before pivot and other is after pivot

public class QuickSort {
   
    public static void main(String args[]) {
        int arr[] = {10,3,16,8,9,1,15,6,18};
        quick_sort(arr,0, arr.length-1);
        System.out.println(Arrays.toString(arr));
    }
   
    static void quick_sort ( int A[ ] ,int start , int end ) {
           if( start < end ) {
                //stores the position of pivot element
                 int piv_pos = partition (A,start , end ) ;    
                 quick_sort (A,start , piv_pos -1);    //sorts the left side of pivot.
                 quick_sort ( A,piv_pos +1 , end) ; //sorts the right side of pivot.
           }
        }
   
    static int partition ( int A[],int start ,int end) {
        int i = start + 1;
        int piv = A[start] ;            //make the first element as pivot element.
        for(int j =start + 1; j <= end ; j++ )  {
        /*rearrange the array by putting elements which are less than pivot
           on one side and which are greater that on other. */

              if ( A[ j ] < piv) {
                     swap (A ,i , j );
                i += 1;
            }
       }
       swap ( A,start ,i-1  ) ;  //put the pivot element in its proper place.
       return i-1;                      //return the position of the pivot
    }
   
    public static void swap(int[] A,int first, int second) {
        int temp = A[first];
        A[first] = A[second];
        A[second] = temp;
    }
   
}


How partition work in above:
start = 0 , end = 10
[5,9,3,15,13,7,1,8,18,14,4]
piv = A[start] = 5
i = start+1 = 1;
loop--> j=start+1 to <=end and j++

first round of loop:  a[j]>piv so nothing change
                                  i= 1, j=2
second round of loop: a[j]<piv so swap i with j and increase i by1
  [5,3,9,15,13,7,1,8,18,14,4]
       i = 2, j=3
third round of loop:  a[j]>piv so nothing change
i=2,j=4 
fourth round of loop:  a[j]>piv so nothing change
i=2,j=5
fifth round of loop:  a[j]>piv so nothing change
i=2,j=6
seventh round of loop: a[j]<piv so swap i with j and increase i by1
  [5,3,1,15,13,7,9,8,18,14,4]
       i = 3, j=7
next few round no change till i=3, j=9
in last round i=3,j=10
a[j]<piv so swap i with j and increase i by1
  [5,3,1,4,13,7,9,8,18,14,15]
       i = 4


now loop break move pivot element to actual position
swap i-1 with start(pivot)

now pivot moved to actual postion

then we will sort the leftside of pivot and right side







Implement Least Recently Used (LRU) cache


 If item is present in cache, it is moved to front of the list and location is returned.

 If it is not present , a new page mapping is done. If cache is not full, a new entry is added to front otherwise least recently used entry is removed and then a new entry to front is added.

import java.util.HashMap;
import java.util.Map;

public class LRUCacheSample1 {
    DoubleLinkList start = null;
    DoubleLinkList end = null;
    int capacity = 5;
    int count = 0;
    Map<Integer, DoubleLinkList> map = new HashMap<>();
    class DoubleLinkList{
        DoubleLinkList next;
        DoubleLinkList prev;
        int key;
        int val;
      
        public DoubleLinkList(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }
  
    void get(int key) {
        if(map.containsKey(key)) {
            DoubleLinkList existNode = map.get(key);
            moveNodeToFront(existNode);
        }
    }
  
    void add(int key,int val) {
        if(map.containsKey(key)) {
            DoubleLinkList existNode = map.get(key);
            existNode.val = val;
            moveNodeToFront(existNode);
        }else {
            DoubleLinkList node = new DoubleLinkList(key, val);
            if(count<capacity) {
                count = count+1;
                addNodeAtFront(node);
            }else {
                DoubleLinkList lastNode = map.remove(end.key);
                removeNode(lastNode);
                addNodeAtFront(node);
            }
      
        }
    }
  
    void removeNode(DoubleLinkList node) {
         end = end.prev;
         if(null!=end) {
             end.next = null;
         }
        node = null;
    }
  
    void addNodeAtFront(DoubleLinkList node) {
        node.next = start;
        if(null!=start) {
            start.prev = node;
        }
            start = node;
         if(end==null) {
             end = node;
         }
         map.put(node.key, node);
        
    }
  
    void moveNodeToFront(DoubleLinkList node) {
        DoubleLinkList pr = node.prev;
        DoubleLinkList nex = node.next;
        if(null!=pr) {
            pr.next = nex;
        }else {
            start = node;
        }
        if(null!=nex) {
            nex.prev = pr;
        }else {
            end = pr;
        }
      
         addNodeAtFront(node);
    }
  
    void print() {
        DoubleLinkList node = start;
        while(null!=node) {
            System.out.println("key is"+node.key+"val is"+node.val);
            node = node.next;
        }
    }
  
  
    public static void main(String args[]) {
        LRUCacheSample1 obj = new LRUCacheSample1();
        obj.add(5, 10);
        obj.add(2, 4);
        obj.add(3, 6);
        obj.add(6, 12);
        obj.add(8, 16);
        
        obj.print();
        obj.get(3);
        System.out.println("*****************");
        System.out.println("after get 3");
        obj.print();
      
        obj.add(9, 18);
        System.out.println("*****************");
        System.out.println("after add 9");
        obj.print();
      
        obj.add(2, 13);
        System.out.println("*****************");
        System.out.println("after update 2");
        obj.print();
      
      
    }
  
}
output::
key is8val is16
key is6val is12
key is3val is6
key is2val is4
key is5val is10
*****************
after get 3
key is3val is6
key is8val is16
key is6val is12
key is2val is4
key is5val is10
*****************
after add 9
key is9val is18
key is3val is6
key is8val is16
key is6val is12
key is2val is4
*****************
after update 2
key is2val is13
key is9val is18
key is3val is6
key is8val is16
key is6val is12

Ref: http://androidsrc.net/lru-cache-java-implementation/

Basics of Log4j

 Log4j is a Java library that specializes in logging.

At its most basic level, you can think of it as a replacement for System.out.println's in your code. Why is it better than System.out.println's? The reasons are numerous.

To begin with, System.out.println outputs to standard output, which typically is a console window. The output from Log4j can go to the console, but it can also go to an email server, a database table, a log file, or various other destinations.

Another great benefit of Log4j is that different levels of logging can be set. The levels are hierarchical and are as follows: TRACE, DEBUG, INFO, WARN, ERROR,


Ref: http://www.avajava.com/tutorials/lessons/what-is-log4j-and-how-do-i-use-it.html

links for Data Structure

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