• Java HashMap Examples

    In this post, I walk through the concept of Java HashMap, and use examples to describe its usage cases. 

    What is HashMap

    Java HashMap is a Hash table based implementation of the Java Map interface.  It provides all of the optional map operations, and permits null values and the null key.  The order of Keys in a HashMap is not guaranteed. So we should not reply on the order of the keys in a HashMap. 

    HashMap vs Hashtable

    Based on java doc, Java HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

    [Read More...]
  • Java Map vs HashMap vs TreeMap vs LinkedHashMap

    Java Map

    Java Map is an interface with the following signature. 

    public interface Map<K,V>

    Here are some properties of Java Map:

    1. It defines an operation to map keys to values.
    2. A map cannot contain duplicate keys; each key can map to at most one value.
    3. The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings.

    4. The order of a map is dependent on its implementations. 

    [Read More...]
  • Count word frequency

    Count word frequency is a popular task for text analysis. In this post, I describe how to count word frequency using Java HashMap, python dictionary, and Spark. 

    Use Java HashMap to Count Word frequency

    {a=5, b=2, c=6, d=3}

    Use Python Dict to count word frequency

    The output:

    {‘a’: 5, ‘c’: 6, ‘b’: 2, ‘d’: 3}

    Use Spark to count word Frequency

    The above method works well for small dataset. However, if you have a huge dataset, the hashTable based method will not work. You will need to develop a distributed program to accomplish this task.

    [Read More...]
  • Java for Loop

    In this post, I describe how to do for loop on an Java ArrayList. Array, and HashMap.

    Java Array for loop

    In the following example, we create an int array, then loop it to add numbers from 1 to 100.  Then we loop it again to calculate the sum of the numbers in the array. 

    Java List for loop

    We provide four ways to show how to loop a java List. 

    iterator.hasNext()
    Value 1
    Value 2
    Value 3
    for loop
    Value 1
    Value 2
    Value 3
    for loop advance
    Value 1
    Value 2
    Value 3
    while advance
    Value 1
    Value 2
    Value 3

    Java HashMap for loop

    If you’re only interested in the keys,

    [Read More...]