Monday, 30 October 2017

Implement case insensitive map

Implement a map that satisfies below conditions.
a.   It should treat keys case insensitively. For example, the key "India", "INDIA", "inDIA" are treated as equal and there is only one entry exist for the keys "India", "INDIA", "inDIA" at any point of time.
b.   It should return the key as it is (do not convert key to lower case (or) upper case while storing)
c.   Maintain the order of insertion.
d.   If the key is not a string, then it should behave like normal map

Before going to read the solution, I would recommend you to go through ‘How HashMap works in Java?’, ‘How LinkedHashMap works in Java?’, ‘How TreeMap works in Java?’

All the crud specific methods like get, put, putAll, containsKey, remove, entrySet, keySet is going to be impacted to implement a map case sensitively.

While inserting a key into the map, we should check whether the key is instance of string or not. If key is instance of string, we need to check, whether any case-insensitive string present or not. If the case insensitive string is already existed in the map, then we should replace that entry with given entry.

There can be multiple implementations possible, but I would like to go with below approach.

I defined new class ‘CaseInsensitiveString’ to wrap string keys.
 private static class CaseInsensitiveString {
  private String key;

  public CaseInsensitiveString(String key) {
   this.key = key;
  }

  @Override
  public int hashCode() {
   if (key == null)
    return 0;

   return key.toUpperCase().hashCode();
  }

  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   CaseInsensitiveString other = (CaseInsensitiveString) obj;
   if (key == null) {
    if (other.key != null)
     return false;
   } else if (!key.toUpperCase().equals(other.key.toUpperCase()))
    return false;
   return true;
  }

  @Override
  public String toString() {
   return key;
  }

 }


If the key is of type string, then I will wrap the string using CaseInsensitiveString object. I override the hashCode and equals method such that, two case-insensitive equal strings always point to same bucket and treated as equal. If you would like to know the relation between equals and hashCode method, I would recommend you to go through ‘Contract between hashCode and equals’.

To satisfy the point c, we should use the LinkedHashMap.

Find the below working application, java documentation on the methods is self-explanatory.


InsensitiveMap.java

package com.sample.collections;

import java.util.AbstractMap;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;


public class InsensitiveMap<K, V> implements Map<K, V> {
 private Map<K, V> map;

 public InsensitiveMap() {
  map = new LinkedHashMap<>();
 }

 /**
  * Convert the object to Case insensitive string.
  * 
  * @param obj
  * @return
  */
 private static CaseInsensitiveString convertObjectToCaseInsensitiveString(Object obj) {
  String keyStr = (String) obj;
  return new CaseInsensitiveString(keyStr);
 }

 @Override
 public int size() {
  return map.size();
 }

 @Override
 public boolean isEmpty() {
  return map.isEmpty();
 }

 @Override
 public boolean containsKey(Object key) {
  if (!(key instanceof String)) {
   return map.containsKey(key);
  }

  return map.containsKey(convertObjectToCaseInsensitiveString(key));
 }

 @Override
 public boolean containsValue(Object value) {
  return map.containsValue(value);
 }

 @Override
 public V get(Object key) {
  if (!(key instanceof String)) {
   return map.get(key);
  }

  return map.get(convertObjectToCaseInsensitiveString(key));
 }

 @Override
 public V put(K key, V value) {
  if (!(key instanceof String)) {
   return map.put(key, value);
  }

  CaseInsensitiveString caseInsensitiveString = convertObjectToCaseInsensitiveString(key);
  return map.put((K) caseInsensitiveString, value);

 }

 @Override
 public V remove(Object key) {
  if (!(key instanceof String)) {
   return map.remove(key);
  }

  return map.remove(convertObjectToCaseInsensitiveString(key));

 }

 @Override
 public void putAll(Map<? extends K, ? extends V> m) {
  if (m == null) {
   return;
  }

  for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
   put(entry.getKey(), entry.getValue());
  }
 }

 @Override
 public void clear() {
  map.clear();
 }

 @Override
 public Set<K> keySet() {

  Set set = new LinkedHashSet();

  for (Object key : map.keySet()) {
   set.add(key instanceof CaseInsensitiveString ? key.toString() : key);
  }
  return set;
 }

 @Override
 public Collection<V> values() {
  return map.values();
 }

 @Override
 public Set<java.util.Map.Entry<K, V>> entrySet() {
  Set<Entry<K, V>> entrySet = map.entrySet();
  Set<Entry<K, V>> outputSet = new LinkedHashSet<Entry<K, V>>();

  for (Entry entry : entrySet) {
   if (!(entry.getKey() instanceof CaseInsensitiveString)) {
    outputSet.add(entry);
   }

   CaseInsensitiveString key = (CaseInsensitiveString) entry.getKey();
   entry = new AbstractMap.SimpleImmutableEntry<K, V>((K) key.toString(), (V) entry.getValue());

  }

  return outputSet;
 }

 private static class CaseInsensitiveString {
  private String key;

  public CaseInsensitiveString(String key) {
   this.key = key;
  }

  @Override
  public int hashCode() {
   if (key == null)
    return 0;

   return key.toUpperCase().hashCode();
  }

  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   CaseInsensitiveString other = (CaseInsensitiveString) obj;
   if (key == null) {
    if (other.key != null)
     return false;
   } else if (!key.toUpperCase().equals(other.key.toUpperCase()))
    return false;
   return true;
  }

  @Override
  public String toString() {
   return key;
  }

 }

}


Test.java

package com.sample.collections;

import java.util.Map;
import java.util.Set;

import com.sample.collections.InsensitiveMap;

public class Test {

 private static void printMap(Map map) {

  Set set = map.keySet();

  for (Object obj : set) {
   System.out.println(obj + " " + map.get(obj));
  }
 }

 public static void main(String args[]) throws CloneNotSupportedException {
  InsensitiveMap<String, String> map = new InsensitiveMap<>();

  map.put("Krishna", "ptr");

  printMap(map);

  map.put("KRIshna", "123");
  printMap(map);

  map.put("KRISHNA", "abcde");
  printMap(map);

 }
}


Output

Krishna ptr
Krishna 123
Krishna abcde



Tuesday, 24 October 2017

How to get shallow copy of array?

clone() method of array return the shallow copy of this array.

Test.java
public class Test {

 public static void printArray(int[] arr) {
  for (int data : arr) {
   System.out.print(data + " ");
  }
 }

 public static void main(String args[]) {
  int[] arr1 = { 2, 3, 5, 7 };
  int[] arr2 = arr1.clone();

  System.out.println("Elements in arr1 are :");
  printArray(arr1);

  System.out.println("\nElements in arr2 are :");
  printArray(arr2);
 }
}


How shallow copy works on reference types?
A shallow copy just copies the values of the references. Lets see it by an example.


Lets take a Student class, which contains 'marks' object and two fields(name, id).
If we clone Student s1 as Student s2. Then fields other than reference variables are copied as separate variables, but the reference variable 'marks' is same for both student s1 and s2. I.e, a shallow copy just copies the values of the references in the class. So changes to the marks object by student s1 is reflected to s2 and vice versa.
Find the below working application.

Marks.java
package com.sample.model;

public class Marks {
 public int maths, physics, chemistry;

 public Marks(int m, int p, int c) {
  maths = m;
  physics = p;
  chemistry = c;
 }
}

Student.java
package com.sample.model;

public class Student implements Cloneable {
 public int id;
 public String name;
 public Marks marks;

 public Student(int id, String name, Marks marks) {
  this.id = id;
  this.name = name;
  this.marks = marks;
 }

 public void printMarks() {
  System.out.println("Maths: " + marks.maths);
  System.out.println("Physics: " + marks.physics);
  System.out.println("Chemistry: " + marks.chemistry);
 }

 @Override
 public String toString() {
  return id + "." + name;
 }

 @Override
 public Object clone() throws CloneNotSupportedException {
  return super.clone();
 }
}

Test.java
package utils;

import com.sample.model.Marks;
import com.sample.model.Student;

public class Test {

 public static void main(String args[]) throws CloneNotSupportedException {
  Marks m1 = new Marks(95, 96, 75);

  Student s1 = new Student(1, "Krishna", m1);
  Student s2 = (Student) s1.clone();

  System.out.println("For student s1");
  System.out.println(s1);
  s1.printMarks();

  System.out.println("\n\nFor student s2");
  System.out.println(s2);
  s2.printMarks();

  System.out.println("\nchange marks of student s2 to 35, 45, and 55");
  s2.marks.maths = 35;
  s2.marks.physics = 45;
  s2.marks.chemistry = 55;

  System.out.println("Change the name to hari and id to 2 for student s2");
  s2.name = "Hari";
  s2.id = 2;

  System.out.println("\n\nFor student s1");
  System.out.println(s1);
  s1.printMarks();

  System.out.println("\n\nFor student s2");
  System.out.println(s2);
  s2.printMarks();
 }
}

Output
For student s1
1.Krishna
Maths: 95
Physics: 96
Chemistry: 75


For student s2
1.Krishna
Maths: 95
Physics: 96
Chemistry: 75

change marks of student s2 to 35, 45, and 55
Change the name to hari and id to 2 for student s2


For student s1
1.Krishna
Maths: 35
Physics: 45
Chemistry: 55


For student s2
2.Hari
Maths: 35
Physics: 45
Chemistry: 55





Monday, 23 October 2017

Delete a directory recursively in Java

In this post, I am going to show you how to delete a directory recursively in Java.

PseudoCode.
Step 1: First check whether given file exists or not.
Step 2: If file is not exist return.
Step 3: If file is a directory, then read all the children from given directory. For every children, if the children is a directory then repeat step 3 and delete the file.

Find the below working application.

FileUtil.java
package utils;

import java.io.File;

public class FileUtil {
 public static void deleteDirectory(String dirName) {
  if (dirName == null || dirName.isEmpty()) {
   throw new IllegalArgumentException("File name shouldn't be empty");
  }
  File file = new File(dirName);

  if (!file.exists()) {
   System.out.println("File is not existed");
   return;
  }

  if (file.isDirectory()) {
   deleteDirectory(file);
   file.delete();
  }

 }

 private static void deleteDirectory(File dir) {

  File[] children = dir.listFiles();

  for (File file : children) {
   if (file.isDirectory()) {
    deleteDirectory(file);
   }
   file.setWritable(true);
   file.delete();
  }

 }
}


Test.java
package utils;

public class Test {

 public static void main(String args[]) {
  String dirName = ""; // Directory absolute path to delete
  FileUtil.deleteDirectory(dirName);

 }
}

Merge generic arrays

In this post, I am going to show you how to merge generic arrays.

First, we need to define a generic array, that takes variable number of generic arrays as arguments and return a generic array. Method signature looks like below.
public static <T> T[] mergeArrays(T[]... arr)


Next, we need to identify the size of the resulting (after merging all the elements of input arrays) array.


Below snippet is used to calculate the length of output array.
  int finalArraySize = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;
   finalArraySize += array.length;
  }

Define generic array with length ‘finalArraySize’. By using reflection, we can define gneric array.
T[] result = (T[]) Array.newInstance(arr[0].getClass().getComponentType(), finalArraySize);

Now, you can copy all the input array elements to result array. I am using System.arraycopy method to copy elements of array.
  int offset = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;

   System.arraycopy(array, 0, result, offset, array.length);
   offset += array.length;
  }


Find the below working application.


Test.java
import java.lang.reflect.Array;

public class Test {
 @SuppressWarnings("unchecked")
 public static <T> T[] mergeArrays(T[]... arr) {
  if (arr == null) {
   return null;
  }
  int finalArraySize = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;
   finalArraySize += array.length;
  }

  /* Define array with given size */
  T[] result = (T[]) Array.newInstance(arr[0].getClass().getComponentType(), finalArraySize);
  int offset = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;

   System.arraycopy(array, 0, result, offset, array.length);
   offset += array.length;
  }

  return result;
 }

 private static void printArray(Object[] arr) {
  for (Object data : arr) {
   System.out.print(data + " ");
  }
 }

 public static void main(String args[]) {
  Integer[] arr1 = { 2, 3, 5, 7 };
  Integer[] arr2 = { 1, 3, 5, 7, 11 };
  Integer[] arr3 = null;
  Integer[] arr4 = { 2, 4, 6, 8, 10 };

  Integer[] result = mergeArrays(arr1, arr2, arr3, arr4);
  printArray(result);

 }
}




Sunday, 22 October 2017

Convert epoch to human readable format

In this post, I am going to explain how to convert epoch time to human readable format.

SimpleDateFormat class provides format method to convert given date into human readable format.

Step 1: Get Date instance from seconds.
Date date = new Date(seconds);

Step 2: Create instance of SimpleDateFormat class.
DateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

Step 3: Use the format method to convert given date into human readable form.
formatter.format(date);

Find the below working application.

Test.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
 public static String getDateFromSeconds(long seconds) {
  Date date = new Date(seconds);
  DateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
  return formatter.format(date);
 }

 public static void main(String args[]) {
  long timeInSeconds = 1508683954000l;

  String date = getDateFromSeconds(timeInSeconds);
  System.out.println(date);
 }
}

Output
2017.10.22 20:22:34

Below are some of the examples to format given date.

"K:mm a, z"
"EEE, d MMM yyyy HH:mm:ss Z"
"yyMMddHHmmssZ"
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
"yyyyy.MMMMM.dd GGG hh:mm aaa"
"hh 'o''clock' a, zzzz"
"yyyy.MM.dd G 'at' HH:mm:ss z"
"EEE, MMM d, ''yy"
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
"YYYY-'W'ww-u"
"h:mm a"

You may like
Interview Questions

Wednesday, 18 October 2017

Convert query string to name value pair (map)

Query string is part of the URL, used to pass the extra information to the request.

Ex
http://example.com/employee?name=devi&city=Ongole

In the above example ‘name=devi&city=Ongole’ is the query string.

Below snippet converts the query string to a map.
 private static Map<String, String> parseQueryString(String queryString) throws UnsupportedEncodingException {
  if (queryString == null || queryString.isEmpty()) {
   return Collections.EMPTY_MAP;
  }

  String[] queryParams = queryString.split("&");
  Map<String, String> map = new HashMap<>();

  for (String queryParam : queryParams) {
   int index = queryParam.indexOf('=');
   String key = queryParam.substring(0, index);
   key = URLDecoder.decode(key, "UTF-8");

   String value = null;

   if (index > 0) {
    value = queryParam.substring(index + 1);
    value = URLDecoder.decode(value, "UTF-8");
   }

   map.put(key, value);
  }

  return map;
 }

Find the below working application.


Test.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Test {

 private static Map<String, String> parseQueryString(String queryString) throws UnsupportedEncodingException {
  if (queryString == null || queryString.isEmpty()) {
   return Collections.emptyMap();
  }

  String[] queryParams = queryString.split("&");
  Map<String, String> map = new HashMap<>();

  for (String queryParam : queryParams) {
   int index = queryParam.indexOf('=');
   String key = queryParam.substring(0, index);
   key = URLDecoder.decode(key, "UTF-8");

   String value = null;

   if (index > 0) {
    value = queryParam.substring(index + 1);
    value = URLDecoder.decode(value, "UTF-8");
   }

   map.put(key, value);
  }

  return map;
 }

 private static void printMap(Map<String, String> map) {
  Set<Map.Entry<String, String>> entrySet = map.entrySet();

  for (Map.Entry<String, String> entry : entrySet) {
   System.out.println(entry.getKey() + " : " + entry.getValue());
  }
 }

 private static void parseAndPrintQueryString(String queryString) throws UnsupportedEncodingException {
  Map<String, String> map = parseQueryString(queryString);
  System.out.println("\nFor the query String : " + queryString);
  printMap(map);
 }

 public static void main(String args[]) throws IOException, ClassNotFoundException {

  String queryString1 = "name=devi&city=Ongole";
  String queryString2 = "name=&city=Ongole";
  String queryString3 = "name=devi&city=";
  String queryString4 = "name=&city=";

  parseAndPrintQueryString(queryString1);
  parseAndPrintQueryString(queryString2);
  parseAndPrintQueryString(queryString3);
  parseAndPrintQueryString(queryString4);
 }
}

Output
For the query String : name=devi&city=Ongole
city : Ongole
name : devi

For the query String : name=&city=Ongole
city : Ongole
name : 

For the query String : name=devi&city=
city : 
name : devi

For the query String : name=&city=
city : 
name :