Median in a stream of integers

After reading 1st element of stream – 5 -> median – 5
After reading 2nd element of stream – 5, 15 -> median – 10
After reading 3rd element of stream – 5, 15, 1 -> median – 5
After reading 4th element of stream – 5, 15, 1, 3 -> median – 4, so on…
Making it clear, when the input size is odd, we take the middle element of sorted data. If the input size is even, we pick average of middle two elements in sorted stream.

public class RunningMedian
{
    PriorityQueue<Integer> upperQueue;
    PriorityQueue<Integer> lowerQueue;

    public RunningMedian()
    {
        lowerQueue=new PriorityQueue<Integer>(
          20,new Comparator<Integer>()
        {

            @Override
            public int compare(Integer o1, Integer o2)
            {

                return (o2-o1);
            }

        });
        upperQueue=new PriorityQueue<Integer>();
        upperQueue.add(Integer.MAX_VALUE);
        lowerQueue.add(Integer.MIN_VALUE);
    }

    public double getMedian(int num)
    {
        //adding the number to proper heap
            if(num>=upperQueue.peek())
                upperQueue.add(num);
            else
                lowerQueue.add(num);
        //balancing the heaps
        if(upperQueue.size()-lowerQueue.size()==2)
            lowerQueue.add(upperQueue.poll());
        else if(lowerQueue.size()-upperQueue.size()==2)
            upperQueue.add(lowerQueue.poll());
        //returning the median
        if(upperQueue.size()==lowerQueue.size())
            return(upperQueue.peek()+lowerQueue.peek())/2.0;
        else if(upperQueue.size()>lowerQueue.size())
            return upperQueue.peek();
        else
            return lowerQueue.peek();

    }
    public static void main(String[] args)
    {
        Random random=new Random();
        RunningMedian runningMedian=new RunningMedian();
        System.out.println("num\tmedian");
        for(int i=0;i<50;++i)
        {
            int num=random.nextInt(100);
            System.out.print(num);
            System.out.print("\t");
            System.out.println(
              runningMedian.getMedian(num));
        }

    }

}

Reverse stack

void rev_stack(Stack <Integer> s)
{
     if( !s.isEmpty() ) return;
     int temp = s.pop();
     rev_stack(s);
     insert_at_bottom(s, temp);
}

public void insert_at_bottom(Stack <Integer> s, int data)
{    
     if (!s.isEmpty()){
          s.push(data);
          return;
     }
     int temp1=s.pop();
     insert_at_bottom(s);
     s.push(temp1);
}

Sort Stack

public void sort(Stack<Integer> s){
    int x=0;
    if (!s.isEmpty()){
        x=s.pop();
        sort(s);
        insert(s,x);
    }
}
public void insert(Stack<Integer> s, int x){
    if (!s.isEmpty() && s.peek()>= x){
        int y=s.pop();
        insert(s, x);
        s.push(y);
    }
    else {
        s.push(x);
    }
}

combine multiple csv files into one excel workbook as different sheets using java

public class csvxls{
    public static void main(String[]args){
    try{
        File folder = new File("F:/csvfiles/");
        File[] listOfFiles = folder.listFiles();
        HSSFWorkbook workbook=new HSSFWorkbook();

        for (File file : listOfFiles) {
            if (file.isFile()) {
                String thisline;
                ArrayList<String> al = null;
                ArrayList<ArrayList<String>> arlist = new ArrayList<ArrayList<String>>();

                HSSFSheet sheet =  workbook.createSheet(file.getName());  
                FileInputStream fis = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));

                while ((thisline = br.readLine()) != null) {
                    al = new ArrayList<String>();
                    String strar[] = thisline.split(",");

                    for (int j = 0; j < strar.length; j++) { 
                        for (int k = 0; k < arlist.size(); k++) {
                            ArrayList<String> ardata = (ArrayList<String>) arlist.get(k);
                            HSSFRow row = sheet.createRow((short) k);

                            for (int p = 0; p < ardata.size(); p++) {
                                HSSFCell cell = row.createCell((short) p);
                                cell.setCellValue(ardata.get(p).toString());
                            }
                        }
                        al.add(strar[j]);
                    } 
                  arlist.add(al);
                }

                fis.close();  
                FileOutputStream fileOut = new FileOutputStream("F://NewWBFile.xls");
                workbook.write(fileOut);
                fileOut.flush();
                fileOut.close();
                br.close();
            }
        }
    System.out.println("Your excel file has been generated!");
    } catch ( Exception ex ) {
        System.out.println(ex);
       }
    }
}

Largest Rectangular Area in a Histogram

int getMaxArea(int hist[], int n)
{
    stack<int> s;
    int max_area = 0;
    int tp;  // To store top of stack
    int area_with_top;
    int i = 0;
    while (i < n)
    {
        // If this bar is higher than the bar on top stack, push it to stack
        if (s.empty() || hist[s.top()] <= hist[i])
            s.push(i++);
        // If this bar is lower than top of stack, then calculate area of rectangle
        // with stack top as the smallest (or minimum height) bar.
        else
        {
            tp = s.top();  // store the top index
            s.pop();  // pop the top
            // Calculate the area with hist[tp] stack as smallest bar
            area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
            if (max_area < area_with_top)
                max_area = area_with_top;
        }
    }
    // Now pop the remaining bars from stack and calculate area with every
    // popped bar as the smallest bar
    while (s.empty() == false)
    {
        tp = s.top();
        s.pop();
        area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
        if (max_area < area_with_top)
            max_area = area_with_top;
    }
    return max_area;
}

Synchronized Threading

import java.util.*;
import java.lang.*;
import java.io.*;
    
class Table{   
    void printTable(int n){  
        synchronized(this){ 
           System.out.println(n);  
        }  
    }  
}
      
class MyThread1 extends Thread {  
    Table t;  
    
    MyThread1(Table t){  
        this.t=t;  
    }  
    
    public void run(){  
        t.printTable(5);  
    }      
}  

class MyThread2 extends Thread{  
    Table t;  
    
    MyThread2(Table t){  
        this.t=t;  
    }  
    
    public void run(){  
        t.printTable(100);  
    }  
}  
      
class TestSynchronizedBlock1{  
    public static void main(String args[]){  
        Table obj = new Table();
        MyThread1 t1=new MyThread1(obj);  
        MyThread2 t2=new MyThread2(obj);  
        t1.start();  
        t2.start();  
    }  
}

Longest Palindromic Subsequence

int lps(char *seq, int i, int j) // i and j are first and last character
{
   // If there is only 1 character
   if (i == j)
     return 1;
 
   // If there are only 2 characters and both are same
   if (seq[i] == seq[j] && i + 1 == j)
     return 2;
 
   // If the first and last characters match
   if (seq[i] == seq[j])
      return lps (seq, i+1, j-1) + 2;
 
   // If the first and last characters do not match
   return max( lps(seq, i, j-1), lps(seq, i+1, j) );
}

Threads

class MultithreadingDemo implements Runnable{  
  public void run(){  
    System.out.println("My thread is in running state.");  
  }   
  public static void main(String args[]){  
     MultithreadingDemo obj=new MultithreadingDemo();  
     Thread tobj =new Thread(obj);  
     tobj.start();  
 }  
}

class MultithreadingDemo extends Thread{  
  public void run(){  
    System.out.println("My thread is in running state.");  
  }   
  public static void main(String args[]){  
     MultithreadingDemo obj=new MultithreadingDemo();   
     obj.start();  
  }  
}

String vs StringBuilder vs StringBuffer

String
String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  . They are thread safe.
StringBuffer

StringBuffer is mutable means one can change the value of the object . Object created through StringBuffer is stored in the heap. Each method in StringBuffer is synchronized that is StringBuffer is thread safe

StringBuilder

StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be modified . StringBuilder is also not thread safe.