Case Insensitive HashMap

 
Array with Even and Odd numbers

This is one of the programming interview questions which asked in recent interview. Need to implement HashMap which will take case insensitive keys. Here we should not confuse with case sensitive, since HashMap by default will hold keys with case sensitive. But as an alternate we need to implement HashMap with Case Insensitive. 
For example: We need to store "abc" and "ABc" in key. Default HashMap will have 2 entries since its case sensitive, where as we need to store only 1 key and value with "abc" with case insensitive. 

So how we can define HashMap with case insensitive? 

We can implement in various ways like implementing Map interface or extending HashMap class etc., In below example we will see about implementing Case Insensitive HashMap by extending HashMap class.


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

public class HashMapCaseInsensitive extends HashMap<String, String>{
 
 @Override
 public String put(String key, String value) {
  return super.put(key.toLowerCase(), value);
 }

 @Override
 public String get(Object key) {
  return super.get(key.toString().toLowerCase());
 }
 
 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMapCaseInsensitive();
  
  hm.put("abc", "one");
  hm.put("ABc", "two");
  hm.put("aBc", "three");
  
  System.out.println("HASHMAP SIZE  : "+hm.size());
  
  System.out.println("GET ABC VALUE : "+hm.get("ABC"));
 }
}


OUTPUT:


HASHMAP SIZE  : 1
GET ABC VALUE : three









Java String

 
Java String

We all know String class in Java is immutable and the value once stored in String Object can't be modified. Also we have discussed about this in our earlier tutorials like difference between String, StringBuffer and StringBuilder and how to create user defined immutable class in Java. We will see how "==" equals operator works on String Object. 

We know that when we apply "==" equals operator on Object it will check only the Object reference rather than values stored in the Object. So using "==" on string Object will result incorrect output and advised to use equals() method which internally overrides hashcode() which will check the values in the Objects using hashing algorithm and gives the correct output.

In this tutorial we will see about how "==" equals operator works internally on string Object with different scenarios. 

Program : 1


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "javadiscover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see in above disassembled code from Java class file, both String references are same. So when we compare these string Objects with "==" operator we will get true. 


Program : 2


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java" + "discover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see both the string Objects are referred by same reference. So we are getting true when we compare by "==" operator. 


Program : 3


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java";
  String str3 = "discover";
  String str4 = str2 + str3;
  System.out.println(str1 == str4);
 }
}

OUTPUT:


false



From above code we can clearly see first 3 string objects are having different references. But 4th "Str4" String in java file contains same value of 1st String "str1" but JDK has created StringBuilder class instead of String with different reference. Hence we are getting false when we compare "str1" and "str4" with "==" operator. 



Grayscale image

 
In our earlier tutorials we have seen about re-sizing image, drawing image border. On same way we will see about how to convert RGB image to Grayscale image using java code. When we talk about RGB to Grayscale we can convert in lot of ways like pixel by pixel, using Java API etc., Even in our below same codes we have tried with 2 ways like using Java Graphics class and next manually reading pixel by pixel and changing the RGB values. 
First lets see by using Graphics class 


import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ColorToGray {

 public static void main(String[] args) {
        
  try {
      File colorImage = new File("D://color.png");
      File grayImage = new File("D://gray.jpg");
      
   BufferedImage cImage = ImageIO.read(colorImage);
   
   BufferedImage image = new BufferedImage(cImage.getWidth(), cImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);  
   Graphics graphics = image.getGraphics();  
   graphics.drawImage(cImage, 0, 0, null);  
   graphics.dispose(); 
   
   ImageIO.write(image, "jpg", grayImage);   
   
        } catch (IOException e) {
   e.printStackTrace();
  } 
 }
}

OUTPUT:

          INPUT FILE                                                             OUTPUT FILE


Color ImageGrayscale Image


Next we will see about reading pixel by pixel and converting RGB to Grayscale which will be time consuming but where we can play around with the pixels value which we want. 


import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Grayscale {
   
    public static void main(String[] args11) throws IOException {
 
        File colorImage = new File("D://color.jpg");
        String grayImage = "D://gray.jpg";
        
        BufferedImage cImage = ImageIO.read(colorImage);
        BufferedImage gImage = new BufferedImage(cImage.getWidth(), cImage.getHeight(), cImage.getType());
        
        for(int i=0; i<cImage.getWidth(); i++) {
            
         for(int j=0; j<cImage.getHeight(); j++) {
 
                int alpha = new Color(cImage.getRGB(i, j)).getAlpha();
                int red = new Color(cImage.getRGB(i, j)).getRed();
                int green = new Color(cImage.getRGB(i, j)).getGreen();
                int blue = new Color(cImage.getRGB(i, j)).getBlue();
 
                
                int gray = (red + green + blue) / 3; 
                red = green = blue = gray;
                gray = (alpha << 24) + (red << 16) + (green << 8) + blue;
                
                gImage.setRGB(i,j,gray);
 
            }
        }
        
        ImageIO.write(gImage, "jpg", new File(grayImage));
    }
 }

OUTPUT:

          INPUT FILE                                                             OUTPUT FILE

Grayscale ImageColor Image




















Boxing and Unboxing

Boxing and Unboxing

Boxing and Unboxing in java is nothing but conversion from Wrapper classes to primitive datatypes and vice-verse in Java. In our earlier tutorial we have seen about list of Wrapper classes and their corresponding primitive datatypes in Java
In that tutorial already we have seen about 8 wrapper classes and their class hierarchy also. So what is Boxing and Unboxing is when we convert an int to an Integer, a double to a Double etc., is called as Boxing and opposite conversion like Integer to int, Double to double is called as Unboxing. Now lets see simple example of both Boxing and Unboxing in java.



public class BoxingTest {

 public static void main(String[] args) {
 
  int _int = 1;
  byte _byte = 2;
  short _short = 3;
  long _long = 4;
  float _float = 5.5f;
  double _double = 6;
  char _char = 'a';
  boolean _boolean = true;
  
  
  // Boxing (Primitive datatype to Wrapper classes)
  Integer w_int = new Integer(_int); 
  Byte w_byte = new Byte(_byte);
  Short w_short = new Short(_short);
  Long w_long = new Long(_long);
  Float w_float = new Float(_float);
  Double w_double = new Double(_double);
  Character w_char = new Character(_char);
  Boolean w_boolean = new Boolean(_boolean);
 
  
  
  // Unboxing (Wrapper class to Primitive datatypes)
  int _int1 = w_int;
  byte _byte1 = w_byte;
  short _short1 = w_short;
  long _long1 = w_long;
  float _float1 = w_float;
  double _double1 = w_double;
  char _char1 = w_char;
  boolean _boolean1 = w_boolean;
 }
}


In above example we have seen how converting primitive datatype to Wrapper class values is called as Boxing and next same Wrapper class object are stored into Primitive datatype is called as unboxing in java. 


Thread join()

 
Basically Thread.join() method allows one thread to wait for the completion of another thread. Suppose if a Thread "A" is running and when we call A.join(), causes the current thread to halt its execution until A thread terminates or complete its process. By join we can make the current thread to wait for the time as same as sleep() method. Where as timing depends on the Operating System and its not on the time which we can specify. Apart from waiting time join can be interrupt by InterruptedException as same as in sleep in method. 

There are 3 types of join() methods in Java Thread class and they are 

void join()
- Waits for the current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms)
- Waits at most (ms) milliseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms, int ns)
- Waits at most (ms) milliseconds and (ms) nanoseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

Lets see simple example in Java Thread to use join() method and how its works.


public class ThreadJoinTest implements Runnable {
 
 @Override
 public void run() {
  try {
   System.out.println(Thread.currentThread().getName());
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  ThreadJoinTest obj = new ThreadJoinTest();
  for(int i=0;i<10;i++){
   Thread t = new Thread(obj);
   t.start();
   try {
    t.join();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}


OUTPUT:


Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9


If we seen above program we have used t.join() for each Thread which we have created. Since join we have used it makes other thread to wait until current thread to complete. This program will work similar to normal java code without multi-threading implementation. Please try with same code by removing t.join() where we can see normal multi-threading implementation on same Object.

OUTPUT: ( By removing t.join() )


Thread-1
Thread-3
Thread-5
Thread-7
Thread-9
Thread-0
Thread-2
Thread-4
Thread-6
Thread-8




Eclipse shortcuts

Eclipse shortcuts

In this tutorial we will see about few important Eclipse shortcut keys and their uses. In practice most of the time using mouse to choice our operations  will cause more time and it may reduce productivity. Not only in Eclipse using shortcuts in any application or OS level will be preferable which will save time and to perform task more faster. 
In Windows most common shortcuts which we are familiar like Select All ( Ctrl + A ), Cut ( Ctrl + X), Copy ( Ctrl + C) and Paste ( Ctrl + V ).  Even in Eclipse they have followed same shortcuts for Select All, Cut, Copy and Paste. Apart from these shortcuts there are lot of keys which will be useful when we programming. Lets see those shortcuts with their usage, 

File Operation Shortcuts:

Create New File Ctrl+N
New Popup Menu Alt+Shift+N
Open Properties Window Alt+Enter
File Refresh F5
File Rename (First Select file) F2
Print Current File/Program Ctrl+P
Save File Ctrl+S
Save All File Ctrl+Shift+S
Close Current Tab Ctrl+W or Ctrl+F4
Close All Open Tab Ctrl+Shift+W or Ctrl+Shift+F4
Exit Eclipse Alt+F4

Program Window Operation Shortcuts:

Maximize Active Tab/Window Ctrl+M
Select Next Tab/Window Ctrl+F6
Reset Perspective Ctrl+F8
Open Views window Ctrl+F7
Open Editor Drop Down Window Ctrl+E
Previous Edited Window Ctrl+Shift+F6
Previous Perspective Ctrl+Shift+F8
Previous View Ctrl+Shift+F7
Show Ruler Context Menu Ctrl+F10
Show System Menu Alt+-
Show View Menu Ctrl+F10
Open Switch to Editor Window Ctrl+Shift+E

File Edit Operation Shortcuts:

Select All Ctrl+A
Select Enclosing Element Alt+Shift+Up
Select Next Element Alt+Shift+Right
Select Previous Element Alt+Shift+Left
Cut Ctrl+X
Copy Ctrl+C
Paste Ctrl+V
Delete Delete
Delete Line Ctrl+D
Delete Next Word Ctrl+Delete
Delete Previous Word Ctrl+Backspace
Find and Replace Ctrl+F
Find Next Ctrl+K
Find Previous Ctrl+Shift+K
Context Information Ctrl+Shift+Space
Incremental Find Ctrl+J
Incremental Find Reverse Ctrl+Shift+J
Quick Diff Toggle Ctrl+Shift+Q
Quick Fix Ctrl+1
Restore Last Selection Alt+Shift+Down
Toggle Insert Mode Ctrl+Shift+Insert
Content Assist Ctrl+Space
Duplicate Lines Ctrl+Alt+Up
Insert Line Above Current Line Ctrl+Shift+Enter
Insert Line Below Current Line Shift+Enter
Move Lines Down Alt+Down
Move Lines Up Alt+Up
Next Word Ctrl+Right
Previous Word Ctrl+Left
Scroll Line Down Ctrl+Down
Scroll Line Up Ctrl+Up
Select Next Word Ctrl+Shift+Right
Select Previous Word Ctrl+Shift+Left
To Lower Case Ctrl+Shift+Y
To Upper Case Ctrl+Shift+X
Undo Ctrl+Z
Redo Ctrl+Y

Build & Run Operation Shortcuts:

Build All Ctrl+B
Run Ctrl+F11
Debug F11
Display Ctrl+Shift+D
Execute Ctrl+U
Inspect Ctrl+Shift+I
Resume F8
Run Last Launched Ctrl+F11
Run to Line Ctrl+R
Toggle Breakpoint Ctrl+Shift+B
Use Step Filters Shift+F5

TreeSet

 
In our earlier tutorials we have seen about LinkedHashMap and LinkedHashSet with simple examples. Now lets see about TreeSet and its difference between HashSet and also how its works. First lets discuss about the main properties of TreeSet class.

  • TreeSet always holds unique values as same as HashSet.
  • TreeSet implements NavigableSet interface which extends the SortedSet interface. 
  • Values stored in TreeSet will be in ascending order by default, hence its won't maintain insertion order as like LinkedHashSet. 
  • If we need to order the values in descending order then we need to use Collections.reverseOrder() as like in below example. 

Now lets see simple example code which shows how it use TreeSet.


import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetTest {

 public static void main(String[] args) {
  
  // By default value will be sorted in ascending order
  Set<String> tsAsc = new TreeSet<String>();

  // To sort values in descending order 
  Set<String> tsDesc = new TreeSet<String>(Collections.reverseOrder());
  
  tsAsc.add("Daniel");
  tsAsc.add("Chris");
  tsAsc.add("Amit");
  tsAsc.add("Bob");
  
  tsDesc.add("Daniel");
  tsDesc.add("Chris");
  tsDesc.add("Amit");
  tsDesc.add("Bob");
  
  // Printing TreeSet values in Ascending order .
  System.out.println("TreeSet values in Ascending order :::::::::::::::");
  Iterator<String> itr1 = tsAsc.iterator();
  while(itr1.hasNext()){
   System.out.println(itr1.next());
  }
  
  // Printing TreeSet values in Descending order .
  System.out.println("TreeSet values in Descending order :::::::::::::::");
  Iterator<String> itr2 = tsDesc.iterator();
  while(itr2.hasNext()){
   System.out.println(itr2.next());
  }
 }
}


OUTPUT:


TreeSet values in Ascending order :::::::::::::::
Amit
Bob
Chris
Daniel

TreeSet values in Descending order :::::::::::::::
Daniel
Chris
Bob
Amit






LinkedHashSet

In our previous tutorial we have discussed about LinkedHashMap and how its works. In this tutorial we will see about LinkedHashSet and what is the difference between HashMap and how its works. Lets list out the properites of LinkedHashSet

  • LinkedHashSet contains only unique values.
  • LinkedHashSet implements Set interface and extends HashSet class. So it acquires all properites of HashSet class.
  • The only difference between HashSet and LinkedHashSet is insertion order. HashSet won't maintain insertion order, were as LinkedHashSet always maintains the insertion order. 

Now lets see simple example which show how to use LinkedHashSet and difference between HashSet.


import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetTest {
 
 public static void main(String[] args) {
  
  Set<String> hs = new HashSet<String>();
  Set<String> lhs = new LinkedHashSet<String>();
  
  hs.add("one");
  hs.add("two");
  hs.add("three");
  hs.add("three");
  hs.add("four");
  
  lhs.add("one");
  lhs.add("two");
  lhs.add("three");
  lhs.add("three");
  lhs.add("four");
  
  // Printing HashSet values.
  System.out.println("HashSet values :::::::::::::::");
  Iterator<String> itr = hs.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
  
  // Printing LinkedHashSet values.
  System.out.println("LinkedHashSet values :::::::::::::::");
  Iterator<String> itr1 = lhs.iterator();
  while(itr1.hasNext()){
   System.out.println(itr1.next());
  }
 }
}

OUTPUT:


HashSet values :::::::::::::::
two
one
three
four

LinkedHashSet values :::::::::::::::
one
two
three
four


In above program we have added 5 values in HashSet and LinkedHashSet with 1 duplicate value "three". Since Set won't allow duplicate value we can see only once "three" has printed. Next if we see the difference between HashSet and LinkedHashSet, insertion order has not followed in HashSet. But LinkedHashSet maintains the insertion order.