Java/Collections Data Structure/HashMap — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 10:25, 1 июня 2010
Содержание
- 1 Check if a particular key exists in Java HashMap example
- 2 Check if a particular value exists in Java HashMap example
- 3 Clones a map
- 4 Create Java Hashtable from HashMap
- 5 Creating a Copy of a Collection: the objects are not cloned.
- 6 Extended Version of java.util.HashMap that provides an extended get method accpeting a default value.
- 7 For both the keys and values of a map
- 8 For keys of a map
- 9 For values of a map
- 10 Generic hashmap with String as key and Integer as value
- 11 Get key set and value set from map and use Iterator to loop through them
- 12 Get Set view of Keys from Java HashMap example
- 13 Get Size of Java HashMap
- 14 Get Synchronized Map from Java HashMap example
- 15 Hash map for counting references to Object keys.
- 16 Iterate through the values of Java HashMap example
- 17 Remove all values from Java HashMap example
- 18 Remove value from Java HashMap
- 19 Sort an HashMap based on the keys
- 20 Storing Primitive Types in a Collection
- 21 Use Iterator to loop through the map key set
Check if a particular key exists in Java HashMap example
<source lang="java">
import java.util.HashMap; public class Main {
public static void main(String[] args) { HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); boolean blnExists = hMap.containsKey("3"); System.out.println("3 exists in HashMap ? : " + blnExists); }
}
</source>
Check if a particular value exists in Java HashMap example
<source lang="java">
import java.util.HashMap; public class Main {
public static void main(String[] args) { HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); System.out.println(hMap.containsValue("Two")); }
}
</source>
Clones a map
<source lang="java">
import java.util.HashMap; import java.util.Map;
public class Main {
/** * Clones a map. * * @param source the source map * @return the clone of the source map */ public static Map copy(Map source) { if(source == null) { return null; } Map result = new HashMap(); result.putAll(source); return result; }
}
</source>
Create Java Hashtable from HashMap
<source lang="java">
import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; public class Main {
public static void main(String[] args) { HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("1", "REPLACED !!"); ht.put("4", "Four"); Enumeration e = ht.elements(); while (e.hasMoreElements()){ System.out.println(e.nextElement()); } ht.putAll(hMap); e = ht.elements(); while (e.hasMoreElements()){ System.out.println(e.nextElement()); } }
}
</source>
Creating a Copy of a Collection: the objects are not cloned.
<source lang="java">
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; public class Main {
public static void main(String[] argv) throws Exception { List stuff = Arrays.asList(new String[] { "a", "b" }); List list = new ArrayList(stuff); List list2 = new LinkedList(list); Set set = new HashSet(stuff); Set set2 = new TreeSet(set); Map map = new HashMap(); Map map2 = new TreeMap(map); }
}
</source>
Extended Version of java.util.HashMap that provides an extended get method accpeting a default value.
<source lang="java">
/*
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
import java.util.Map; /**
* Extended Version of {@link java.util.HashMap} that provides an extended * get method accpeting a default value. The default value is returned if * the map does not contain a value for the provided key. * * @version $Id: HashMap.java 587751 2007-10-24 02:41:36Z vgritsenko $ */
public class HashMap extends java.util.HashMap {
public HashMap () { super(); } public HashMap ( int initialCapacity ) { super(initialCapacity); } public HashMap ( int initialCapacity, float loadFactor ) { super(initialCapacity, loadFactor); } public HashMap ( Map t) { super(t); } /** * Get method extended by default object to be returned when key * is not found. * * @param key key to look up * @param _default default value to return if key is not found * @return value that is associated with key */ public Object get( Object key, Object _default ) { if (this.containsKey(key)) { return this.get(key); } return _default; }
}
</source>
For both the keys and values of a map
<source lang="java">
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map map = new HashMap(); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); } }
}
</source>
For keys of a map
<source lang="java">
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map map = new HashMap(); for (Iterator it = map.keySet().iterator(); it.hasNext();) { Object key = it.next(); } }
}
</source>
For values of a map
<source lang="java">
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map map = new HashMap(); for (Iterator it = map.values().iterator(); it.hasNext();) { Object value = it.next(); } }
}
</source>
Generic hashmap with String as key and Integer as value
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.*; public class Freq {
public static void main(String[] args) { Map<String, Integer> m = new HashMap<String, Integer>(); // Initialize frequency table from command line for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + " distinct words:"); System.out.println(m); }
}
</source>
Get key set and value set from map and use Iterator to loop through them
<source lang="java">
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class HashMapExample {
public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(new Integer(1), "One"); map.put(new Integer(2), "Two"); map.put(new Integer(3), "Three"); map.put(new Integer(4), "Four"); map.put(new Integer(5), "Five"); System.out.println("Map Values Before: "); Set keys = map.keySet(); for (Iterator i = keys.iterator(); i.hasNext();) { Integer key = (Integer) i.next(); String value = (String) map.get(key); System.out.println(key + " = " + value); } System.out.println("\nRemove element with key 6"); map.remove(new Integer(6)); System.out.println("\nMap Values After: "); keys = map.keySet(); for (Iterator i = keys.iterator(); i.hasNext();) { Integer key = (Integer) i.next(); String value = (String) map.get(key); System.out.println(key + " = " + value); } }
}
</source>
Get Set view of Keys from Java HashMap example
<source lang="java">
import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class Main {
public static void main(String[] args) { HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); Set st = hMap.keySet(); Iterator itr = st.iterator(); while (itr.hasNext()) System.out.println(itr.next()); // remove 2 from Set st.remove("2"); System.out.println(hMap.containsKey("2")); }
}
</source>
Get Size of Java HashMap
<source lang="java">
import java.util.HashMap; public class Main {
public static void main(String[] args) { HashMap<String,String> hMap = new HashMap<String,String>(); System.out.println("Size of HashMap : " + hMap.size()); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); System.out.println("Size of HashMap after addition : " + hMap.size()); // remove one element from HashMap System.out.println(hMap.remove("2")); }
}
</source>
Get Synchronized Map from Java HashMap example
<source lang="java">
import java.util.Collections; import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] args) { HashMap hashMap = new HashMap(); Map map = Collections.synchronizedMap(hashMap); }
}
</source>
Hash map for counting references to Object keys.
<source lang="java">
/*
* Copyright (c) 2006-2007, Dennis M. Sosnoski. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of * JiBX nor the names of its contributors may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Iterator;
/**
* Hash map for counting references to Object
keys. The map implementation is not very efficient when
* resizing, but works well when the size of the map is known in advance or when accesses are substantially more common
* than adds.
*
* @author Dennis M. Sosnoski
*/
public class ReferenceCountMap {
/** Default fill fraction allowed before growing table. */ private static final double DEFAULT_FILL = 0.3d; /** Minimum size used for hash table. */ private static final int MINIMUM_SIZE = 63; /** Number of entries present in table. */ private int m_entryCount; /** Entries allowed before growing table. */ private int m_entryLimit; /** Size of array used for keys. */ private int m_arraySize; /** Offset added (modulo table size) to slot number on collision. */ private int m_hitOffset; /** Array of key table slots. */ private Object[] m_keyTable; /** Array of value table slots. */ private int[] m_valueTable; /** * Constructor with count. * * @param count number of values to assume in initial sizing of table */ public ReferenceCountMap(int count) { // compute initial table size (ensuring odd) m_arraySize = Math.max((int)(count / DEFAULT_FILL), MINIMUM_SIZE); m_arraySize += (m_arraySize + 1) % 2; // initialize the table information m_entryLimit = (int)(m_arraySize * DEFAULT_FILL); m_hitOffset = m_arraySize / 2; m_keyTable = new Object[m_arraySize]; m_valueTable = new int[m_arraySize]; } /** * Default constructor. */ public ReferenceCountMap() { this(0); } /** * Copy (clone) constructor. * * @param base instance being copied */ public ReferenceCountMap(ReferenceCountMap base) { // copy the basic occupancy information m_entryCount = base.m_entryCount; m_entryLimit = base.m_entryLimit; m_arraySize = base.m_arraySize; m_hitOffset = base.m_hitOffset; // copy table of items m_keyTable = new Object[m_arraySize]; System.arraycopy(base.m_keyTable, 0, m_keyTable, 0, m_arraySize); m_valueTable = new int[m_arraySize]; System.arraycopy(base.m_valueTable, 0, m_valueTable, 0, m_arraySize); } /** * Step the slot number for an entry. Adds the collision offset (modulo the table size) to the slot number. * * @param slot slot number to be stepped * @return stepped slot number */ private final int stepSlot(int slot) { return (slot + m_hitOffset) % m_arraySize; } /** * Find free slot number for entry. Starts at the slot based directly on the hashed key value. If this slot is * already occupied, it adds the collision offset (modulo the table size) to the slot number and checks that slot, * repeating until an unused slot is found. * * @param slot initial slot computed from key * @return slot at which entry was added */ private final int freeSlot(int slot) { while (m_keyTable[slot] != null) { slot = stepSlot(slot); } return slot; } /** * Standard base slot computation for a key. * * @param key key value to be computed * @return base slot for key */ private final int standardSlot(Object key) { return (key.hashCode() & Integer.MAX_VALUE) % m_arraySize; } /** * Standard find key in table. This method may be used directly for key lookup using either the *hashCode()
method defined for the key objects or theSystem.identityHashCode()
* method, and either theequals()
method defined for the key objects or the==
* operator, as selected by the hash technique constructor parameter. To implement a hash class based on some other * methods of hashing and/or equality testing, define a separate method in the subclass with a different name and * use that method instead. This avoids the overhead caused by overrides of a very heavily used method. * * @param key to be found in table * @return index of matching key, or-index-1
of slot to be used for inserting key in table if not * already present (always negative) */ private int standardFind(Object key) { // find the starting point for searching table int slot = standardSlot(key); // scan through table to find target key while (m_keyTable[slot] != null) { // check if we have a match on target key if (m_keyTable[slot].equals(key)) { return slot; } else { slot = stepSlot(slot); } } return -slot - 1; } /** * Reinsert an entry into the hash map. This is used when the table is being directly modified, and does not adjust * the count present or check the table capacity. * * @param slot position of entry to be reinserted into hash map * @returntrue
if the slot number used by the entry has has changed,false
if not */ private boolean reinsert(int slot) { Object key = m_keyTable[slot]; m_keyTable[slot] = null; return assignSlot(key, m_valueTable[slot]) != slot; } /** * Internal remove pair from the table. Removes the pair from the table by setting the key entry to *null
and adjusting the count present, then chains through the table to reinsert any other pairs * which may have collided with the removed pair. If the associated value is an object reference, it should be set * tonull
before this method is called. * * @param slot index number of pair to be removed */ private void internalRemove(int slot) { // delete pair from table m_keyTable[slot] = null; m_entryCount--; while (m_keyTable[(slot = stepSlot(slot))] != null) { // reinsert current entry in table to fill holes reinsert(slot); } } /** * Restructure the table. This is used when the table is increasing or decreasing in size, and works directly with * the old table representation arrays. It inserts pairs from the old arrays directly into the table without * adjusting the count present or checking the table size. * * @param keys array of keys * @param values array of values */ private void restructure(Object[] keys, int[] values) { for (int i = 0; i < keys.length; i++) { if (keys[i] != null) { assignSlot(keys[i], values[i]); } } } /** * Assign slot for entry. Starts at the slot found by the hashed key value. If this slot is already occupied, it * steps the slot number and checks the resulting slot, repeating until an unused slot is found. This method does * not check for duplicate keys, so it should only be used for internal reordering of the tables. * * @param key to be added to table * @param value associated value for key * @return slot at which entry was added */ private int assignSlot(Object key, int value) { int offset = freeSlot(standardSlot(key)); m_keyTable[offset] = key; m_valueTable[offset] = value; return offset; } /** * Increment a use count in the table. If the key object is already present in the table this adds one to the * reference count; if not present, this adds the key with an initial reference count of one. * * @param key referenced object (non-null
) * @return incremented use count */ public int incrementCount(Object key) { // first validate the parameters if (key == null) { throw new IllegalArgumentException("null key not supported"); } else { // check space available int min = m_entryCount + 1; if (min > m_entryLimit) { // find the array size required int size = m_arraySize; int limit = m_entryLimit; while (limit < min) { size = size * 2 + 1; limit = (int)(size * DEFAULT_FILL); } // set parameters for new array size m_arraySize = size; m_entryLimit = limit; m_hitOffset = size / 2; // restructure for larger arrays Object[] keys = m_keyTable; m_keyTable = new Object[m_arraySize]; int[] values = m_valueTable; m_valueTable = new int[m_arraySize]; restructure(keys, values); } // find slot of table int offset = standardFind(key); if (offset >= 0) { // replace existing value for key return ++m_valueTable[offset]; } else { // add new pair to table m_entryCount++; offset = -offset - 1; m_keyTable[offset] = key; m_valueTable[offset] = 1; return 1; } } } /** * Find an entry in the table. * * @param key key for entry to be returned * @return value for key, or zero if key not found */ public final int getCount(Object key) { int slot = standardFind(key); if (slot >= 0) { return m_valueTable[slot]; } else { return 0; } } /** * Get number of entries in map. * * @return entry count */ public int size() { return m_entryCount; } /** * Get iterator for keys in map. The returned iterator is not safe, so the iterator behavior is undefined if the map * is modified. * * @return iterator */ public Iterator iterator() { return SparseArrayIterator.buildIterator(m_keyTable); } /** * Get array of keys in map. * * @return key array */ public Object[] keyArray() { Object[] keys = new Object[m_entryCount]; int fill = 0; for (int i = 0; i < m_arraySize; i++) { if (m_keyTable[i] != null) { keys[fill++] = m_keyTable[i]; } } return keys; } /** * Construct a copy of the table. * * @return shallow copy of table */ public Object clone() { return new ReferenceCountMap(this); } /** * Clear all keys and counts. */ public void clear() { for (int i = 0; i < m_keyTable.length; i++) { if (m_keyTable[i] != null) { m_keyTable[i] = null; m_valueTable[i] = 0; } } }
} /*
* Copyright (c) 2000-2007, Dennis M. Sosnoski. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. Redistributions in binary * form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of JiBX nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
/**
* Iterator class for sparse values in an array. This type of iterator
* can be used for an object array which has references interspersed with
* null
s.
*
* @author Dennis M. Sosnoski
*/
class SparseArrayIterator implements Iterator
{
/** Empty iterator. */ public static final SparseArrayIterator EMPTY_ITERATOR = new SparseArrayIterator(new Object[0]); /** Array supplying values for iteration. */ private Object[] m_array; /** Offset of next iteration value. */ private int m_offset; /** * Internal constructor. * * @param array array containing values to be iterated */ private SparseArrayIterator(Object[] array) { m_array = array; m_offset = -1; advance(); } /** * Advance to next iteration value. This advances the current position in * the array to the next non-null
value. * * @returntrue
if element available,false
if * not */ protected boolean advance() { while (++m_offset < m_array.length) { if (m_array[m_offset] != null) { return true; } } return false; } /** * Check for iteration element available. * * @returntrue
if element available,false
if * not */ public boolean hasNext() { return m_offset < m_array.length; } /** * Get next iteration element. * * @return next iteration element * @exception NoSuchElementException if past end of iteration */ public Object next() { if (m_offset < m_array.length) { Object result = m_array[m_offset]; advance(); return result; } else { throw new RuntimeException("No such method"); } } /** * Remove element from iteration. This optional operation is not supported * and always throws an exception. * * @exception UnsupportedOperationException for unsupported operation */ public void remove() { throw new UnsupportedOperationException(); } /** * Build iterator. * * @param array array containing values to be iterated (may be *null
) * @return constructed iterator */ public static Iterator buildIterator(Object[] array) { if (array == null || array.length == 0) { return EMPTY_ITERATOR; } else { return new SparseArrayIterator(array); } }
}
</source>
Iterate through the values of Java HashMap example
<source lang="java">
import java.util.Collection; import java.util.HashMap; import java.util.Iterator; public class Main {
public static void main(String[] args) { HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); Collection c = hMap.values(); Iterator itr = c.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }
} /* Three Two One
- /
</source>
Remove all values from Java HashMap example
<source lang="java">
import java.util.HashMap; public class Main {
public static void main(String[] args) { HashMap<String,String> hMap = new HashMap<String,String>(); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); hMap.clear(); System.out.println(hMap.size()); }
}
</source>
Remove value from Java HashMap
<source lang="java">
import java.util.HashMap; public class Main {
public static void main(String[] args) { HashMap<String,String> hMap = new HashMap<String,String>(); hMap.put("1", "One"); hMap.put("2", "Two"); hMap.put("3", "Three"); Object obj = hMap.remove("2"); System.out.println(obj + " Removed from HashMap"); }
}
</source>
Sort an HashMap based on the keys
<source lang="java">
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Main {
public static void main(String[] a) { Map<String, String> yourMap = new HashMap<String, String>(); yourMap.put("1", "one"); yourMap.put("2", "two"); yourMap.put("3", "three"); Map<String, String> sortedMap = new TreeMap<String, String>(yourMap); System.out.println(sortedMap); }
} //{1=one, 2=two, 3=three}
</source>
Storing Primitive Types in a Collection
<source lang="java">
import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map map = new HashMap(); // Create int wrapper object Integer refInt = new Integer(123); // Store int in map map.put("key", refInt); // Get int value from map refInt = (Integer) map.get("key"); // Get the integer value from wrapper object int i = refInt.intValue(); }
}
</source>
Use Iterator to loop through the map key set
<source lang="java">
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main {
public static void main(String[] args) { Map errors = new HashMap(); errors.put("404", "A."); errors.put("403", "B."); errors.put("500", "C."); String errorDesc = (String) errors.get("404"); System.out.println("Error 404: " + errorDesc); Iterator iterator = errors.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); System.out.println("Error " + key + " means " + errors.get(key)); } }
}
</source>