Java Tutorial/Collections/HashMap — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 08:04, 1 июня 2010

Содержание

Adding Key-Value Pairs: public Object put(Object key, Object value)

   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   System.out.println(map);
 }

}</source>



{key1=value1, key3=value3, key2=value2}


Check if a particular key exists in 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");
   boolean blnExists = hMap.containsKey("3");
   System.out.println("3 exists in HashMap ? : " + blnExists);
 }

}</source>





Check if a particular value exists in 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");
   System.out.println(hMap.containsValue("Two"));
 }

}</source>





Checking Hash Maps for Equality: public boolean equals(Object o)

Two maps are defined as equal if both of their entry sets are equal (thisHash.entrySet().equals(map.entrySet()).



   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   Map map2 = new HashMap();
   map2.put("key2", "value2");
   map2.put("key1", "value1");
   map2.put("key3", "value3");
   System.out.println(map2.equals(map2));
 }

}</source>



true


Cloning Hash Map: public Object clone()

   <source lang="java">

import java.util.HashMap; public class MainClass {

 public static void main(String[] a) {
   HashMap map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   HashMap map2 = (HashMap)map.clone();
   System.out.println(map2);
 }

}</source>



{key1=value1, key3=value3, key2=value2}


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>





Displaying Contents: public String toString()

   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   System.out.println(map);
 }

}</source>



{key1=value1, key3=value3, key2=value2}


Fetching Keys and Values: find a value based upon a specific key with: public Object get(Object key)

  1. If is not found, null is returned.
  2. Or, the current value for the key is returned.



   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   System.out.println(map.get("key2"));
 }

}</source>



value2


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>





Get Set view of Keys from HashMap

   <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 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 HashMap

   <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>





Getting the set of all keys with the keySet() method: public Set keySet()

   <source lang="java">

import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   map.put(null, null);
   Set set = map.keySet();
   Iterator iter = set.iterator();
   while (iter.hasNext()) {
     System.out.println(iter.next());
   }
 }

}</source>



key1
key3
null
key2


HashMap Class: a basic key-value map where the elements are unordered

A Map is a storage that hold key to value mappings. There cannot be duplicate keys in a Map and each key maps to at most one value. HashMap is unsynchronized and Hashtable is synchronized. HashMap is the faster one between the two. If you need to maintain map keys in an ordered fashion, you can use TreeMap.

Creating a HashMap



   <source lang="java">

public HashMap() public HashMap(int initialCapacity) public HashMap(int initialCapacity, float loadFactor)</source>





How do I...Store simple pairs of data for quick lookup?

   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String args[]) {
   String[] names = { "A", "J", "B", "E", "P" };
   String[] ids = { "1", "2", "9", "8", "7" };
   Map<String, String> IDMap = new HashMap<String, String>();
   for (int i = 0; i < names.length; i++)
     IDMap.put(ids[i], names[i]);
   System.out.println(IDMap.size() + " Students entered: ");
   System.out.println(IDMap);
 }

}</source>



5 Students entered: 
{7=P, 2=J, 9=B, 8=E, 1=A}


If key is not in add the key value pair

   <source lang="java">

import java.util.HashMap; import java.util.Map; import java.util.Random; class Counter {

 int i = 1;
 public String toString() {
   return Integer.toString(i);
 }

} public class MainClass {

 private static Random rand = new Random();
 public static void main(String[] args) {
   Map hm = new HashMap();
   for (int i = 0; i < 10000; i++) {
     // Produce a number between 0 and 20:
     Integer r = new Integer(rand.nextInt(20));
     if (hm.containsKey(r))
       ((Counter) hm.get(r)).i++;
     else
       hm.put(r, new Counter());
   }
   System.out.println(hm);
 }

}</source>





Iterate through the values of HashMap

   <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>





Removal of all elements from a map: public void clear()

   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   map.clear();
   System.out.println(map);
 }

}</source>



{}


Remove value from 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>





Removing Key-Value Pairs: public Object remove(Object key)

  1. If the key is present, the key-value pair will be removed and the value object will be returned.
  2. If the object is not present in the map, null will be returned.



   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   map.remove("key3");
   System.out.println(map);
 }

}</source>



{key1=value1, key2=value2}


Serializing Hash Maps

   <source lang="java">

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; public class MainClass {

 public static void main(String[] a) throws Exception {
   List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
   FileOutputStream fos = new FileOutputStream("list.ser");
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   oos.writeObject(list);
   oos.close();
   FileInputStream fis = new FileInputStream("list.ser");
   ObjectInputStream ois = new ObjectInputStream(fis);
   List anotherList = (List) ois.readObject();
   ois.close();
   System.out.println(anotherList);
 }

}</source>



[A, B, C, D]


Sizing Hash Maps: find out the number of key-value pairs within the HashMap

   <source lang="java">

public int size() public boolean isEmpty()</source>



3


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>





To copy all the key-value pairs from one Map into another: public void putAll(Map map)

   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   map.put(null, null);
   Map map2 = new HashMap();
   map2.put("key4", "value4");
   map2.put("key5", "value5");
   map2.put("key6", "value6");
   map.putAll(map2);
   System.out.println(map);
 }

}</source>



{key1=value1, key3=value3, key6=value6, null=null, key5=value5, key2=value2, key4=value4}

The value is replaced for every key in the passed-in map that already exists in the HashMap.


To get a set of Map.Entry elements back from a HashMap: public Set entrySet()

   <source lang="java">

import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   Set set = map.entrySet();
   Iterator iter = set.iterator();
   while (iter.hasNext()) {
     Map.Entry entry = (Map.Entry) iter.next();
     System.out.println(entry.getKey() + " -- " + entry.getValue());
   }
 }

}</source>



key1 -- value1
key3 -- value3
key2 -- value2


To get the set of all the values in the hash map: public Collection values()

   <source lang="java">

import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   Collection set = map.values();
   Iterator iter = set.iterator();
   while (iter.hasNext()) {
     System.out.println(iter.next());
   }
 }

}</source>



value1
value3
value2


Unlike a Hashtable, both the key and the value for a HashMap can be null

   <source lang="java">

import java.util.HashMap; import java.util.Map; public class MainClass {

 public static void main(String[] a) {
   Map map = new HashMap();
   map.put("key1", "value1");
   map.put("key2", "value2");
   map.put("key3", "value3");
   map.put(null, null);
   System.out.println(map);
 }

}</source>



{key1=value1, key3=value3, null=null, key2=value2}


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>