Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, December 8, 2011

JSON Parsing in java with Jackson

When it comes to API data and results (like google APIs), json is of great favor to java developers. There are more than 50 libraries for json processing in different languages. To get an overview of json structure and access the libraries, please refer to http://www.json.org/.

Jackson offers three alternative methods for processing JSON:
  • Streaming API reads and writes JSON content as discrete events.
  • Tree Model provides a mutable in-memory tree representation of a JSON document.
  • Data Binding converts JSON to and from POJOs based either on property accessor conventions or annotations.

For a known structure of API return and the requirement to reconstruct similar data skeleton, it would be effortless if Tree Model is used for the recovery.

To download the latest version of Jackson, please refer to:http://wiki.fasterxml.com/JacksonDownload. Both jackson.core and jackson.mapper will be needed for Tree Model processing.

To add the dependencies from internal jars in Eclipse, refer to:How to Add JARs to Project Build Paths in Eclipse

Tree Model Processing Step by Step

Tuesday, November 29, 2011

Iterate over a Map(HashMap) in Java

Here are three methods of iterating through a Map(HashMap) in Java and their pros and cons. They all works for any map implementation in Java, e.g. HashMap, TreeMap, HashTable,LinkedHashMap.

Method #1
Iterating over Entries
Map<Integer, Integer>; map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
pros : You can get both keys and values via entrySet().
cons: NullPointerException will be thrown if you try to iterate over a null map. You should always check for null references before iterating.

Method #2
Iterating over either Key or Value Sets
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

//iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
pros: If all you need is either key sets or value sets, this method is about 10% faster than iteration over entrySet(), and also cleaner.
cons: The same as above

Method #3
Iterating using Iterator
--With Generics
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
--Without Generics
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
The same method can be used for obtaining the key and value sets respectively. Its performance is equal to for-each loop.
pros: It is the only way if you want to remove entries during iteration by implementing iterator.remove(). If you do this in for-each loop, you will get unpredictable results.
cons: Look a little redundant than other methods.

Method #4
Iterating over key sets and search values (inefficient)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
Getting values by keys is inefficient and time-consuming, in different Maps it can be 20% to 200% slower than Method #1.

Sunday, October 9, 2011

Frequently used Java code blocks for Interview or code test

Get a string from standard input
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
String s = buffer.readLine();
Type cast a String to int
String str = "123";
Integer.parseInt(str);
Type cast a String to double
String str = "123.45";
Double D = Double.valueOf(str);
double d = D.doubleValue();
Bubble Sort
public void bubbleSort(int[] arr) {
    boolean swapped = true;
    for (int j = 1; swapped; j++){
        swapped = false;
        for (int i = 0; i < arr.length - j; i++) {
            if (arr[i] > arr[i + 1]) {                          
                int tmp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = tmp;
                swapped = true;
            }
        }                
    }
}
Selection Sort
public void selectionSort(int[] arr){
    for(int j=0; j<arr.length-1; j++){
        int min = j;
        for(i=j+1; i<arr.length; i++)
            if(arr[i] < arr[min])
                min = in;
        swap(arr[j],arr[min]);
    }
}