Find word in a file

br = new BufferedReader(new FileReader(filePath));
        try {
            while((line = br.readLine()) != null)
            {
                String[] words = line.split(" ");

                for (String word : words) {
                  if (word.equals(inputSearch)) {
                    count++;
                  }
              }
          }
      }

OR

br = new BufferedReader(new FileReader(filePath));
        try {
            while((line = br.readLine()) != null)
            {
                  if (line.contains(inputSearch)) {
                    count++;
                  }
             }
         }
    }

HashCode() and equals()

hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.
equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.

  1. Always use same attributes of an object to generate hashCode() and equals() both. As in our case, we have used employee id.
  2. equals() must be consistent (if the objects are not modified, then it must keep returning the same value).
  3. Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
  4. If two objects have the same hashcode, they may or may not be equal.
  5. If you override one, then you should override the other.

The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:

String obj1 = new String("xyz");
String obj2 = new String("xyz");

obj1==obj2 is FALSE

String obj1 = new String("xyz");
// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;

obj1==obj2 is TRUE

The equals() method
equals method is actually meant to compare the contents of 2 objects, and not their location in memory.

String obj1 = new String("xyz");
String obj2 = new String("xyz");

obj1.equals(obj2) is TRUE

by default equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

Autoboxing

Autoboxing and unboxing is introduced in Java 1.5 to automatically convert primitive type into boxed primitive( Object or Wrapper class). autoboxing allows you to use primitive and object type interchangeably in Java on many places like assignment, method invocation etc.

ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1); //autoboxing – primitive to object
intList.add(2); //autoboxing

Segregate even and odd nodes in a Linked List

struct node *reverse(struct node **head)
{
    struct node *curr=*head;
    struct node *prev=NULL;
    truct node *next;
    while(curr!=NULL)
    {
        next=curr->next;
        curr->next=prev;
        prev=curr;
        curr=next;
    }
    return prev;
}
 
struct node *segregateEvenOdd(struct node **head_ref)
{
    struct node *curr = *head_ref;
    struct node *even=NULL,*odd=NULL,*evenh,*oddh;
 
    while(curr!=NULL)
    { 
        if(curr->data%2==0)
        {
            push(&even,curr->data);
        }
        else
        {
            push(&odd,curr->data);
        }
        curr=curr->next;
    }
    evenh=reverse(&even);
    struct node *temp=evenh;
    oddh=reverse(&odd);
    
    while(temp->next!=NULL)
    {
        temp=temp->next;
    }
    temp->next=oddh;
 
    return evenh;
}

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);
    }
}