Free, tested & ready to use examples!
Web - convert files and webpages to any format!

Java HashMap example

Java class HashMap(java.util.HashMap) is a fast and easy to use class representing hash table, a data structure that associates keys with values.
  • Sun Java 1.5 or higher (because this example uses generics and for-each loop)
  • The two most important HashMap's methods are:

    • get( Object key ) - returns the value associated with specified key in this hash map, or null if there is no value for this key
    • put(K key, V value) - associates the specified value with the specified key in this map

    There are some other useful HashMap's methods:

    • containsKey(Object key) - (boolean) returns true if this map contains a value for the specified key
    • values() - returns a collection of the values contained in this map
    • keySet() - returns a set view of the keys contained in this map
    • remove(Object key) - removes the mapping for key from this map if present
    • isEmpty() - (boolean) returns true if this map contains no key-value mappings

    Following example opens file specified in FileReader's object constructor and calculates number of occurrences for each latin-letter word (assuming that words are separated by any non-letter characters)

    source code: Java
    import java.util.ArrayList; 
    import java.util.Collections; 
    import java.util.HashMap; 
    public class HashMapEx { 
        public static void main(String[] args) { 
            // Creating new HashMap objects 
            // keys are String, values are Integer 
            HashMap<String, Integer> wordcount = new HashMap<String, Integer>();
            try { 
                // Opening file 
                // change "/Users/anyexample/input.txt" to path to your test file  
                BufferedReader in = new BufferedReader(new FileReader( 
                // string buffer for file reading   
                String str;
                // reading line by line from file    
                while ((str = in.readLine()) != null) { 
                    str = str.toLowerCase(); // convert to lower case 
                    // starting index, we'll use this to copy words from string 
                    int idx1 = -1;
                    // process each characters  
                    for (int i = 0; i < str.length(); i++) { 
                        // trigger condition if current character is not letter 
                        // or it is the end of line  
                        if ((!Character.isLetter(str.charAt(i))) || (i + 1 == str.length())) { 
                            // do nothing if previous character was also non-letter 
                            if (i - idx1 > 1) { 
                                // copy word from input string buffer to new variable  
                                // from previous non-letter symbol  
                                // to current symbol which is also non-letter 
                                // if this is a letter(than it is last character in the line  
                                // and we should copy it to word)   
                                if (Character.isLetter(str.charAt(i))) 
                                // copying...  
                                String word = str.substring(idx1 + 1, i);
                                // Check if word is in HashMap 
                                if (wordcount.containsKey(word)) { 
                                    // get number of occurrences for this word 
                                    // increment it  
                                    // and put back again  
                                    wordcount.put(word, wordcount.get(word) + 1);
                                } else { 
                                    // this is first time we see this word, set value '1' 
                                    wordcount.put(word, 1);
                            // remember current position as last non-letter symbol                         
                            idx1 = i;
                // Close buffered reader 
            } catch (Exception e) { 
                // If something unexpected happened  
                // print exception information and quit  
            // This code sorts outputs HashMap sorting it by values 
            // First we're getting values array  
            ArrayList<Integer> values = new ArrayList<Integer>();
            // and sorting it (in reverse order) 
            Collections.sort(values, Collections.reverseOrder());
            int last_i = -1;
            // Now, for each value  
            for (Integer i : values) { 
                if (last_i == i) // without dublicates  
                last_i = i;
                // we print all hash keys  
                for (String s : wordcount.keySet()) { 
                    if (wordcount.get(s) == i) // which have this value  
                        System.out.println(s + ":" + i);
                // pretty inefficient, but works  
  • HashMap stores only object references. That's why, it's impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.
  • For multi-theaded(synchronized) array class use Hashtable (java.lang.Hashtable)
  • tested 
  • JDK 1.5

    © AnyExample 2010-2013
    License | Privacy | Contact