Collections and Generics
Maps
Code
Code that uses a hash map
// create an empty hash map HashMapbooks = new HashMap (); // add three entries books.put("wooz", "Wizard of Oz"); books.put("mbdk", "Moby Dick"); books.put("wuth", "Wuthering Heights"); // print the entries for (Map.Entry book : books.entrySet()) System.out.println(book.getKey() + ": " + book.getValue()); // print the entry whose key is "mbdk" System.out.println("\nCode mbdk is " + books.get("mbdk"));
Resulting output
wuth: Wuthering Heights mbdk: Moby Dick wooz: Wizard of Oz Code mbdk is Moby Dick
Code that uses a tree map
// create an empty tree map TreeMapbooks = new TreeMap (); // add three entries books.put("wooz", "Wizard of Oz"); books.put("mbdk", "Moby Dick"); books.put("wuth", "Wuthering Heights"); // print the entries for (Map.Entry book : books.entrySet()) System.out.println(book.getKey() + ": " + book.getValue()); // print the entry whose key is "mbdk" System.out.println("\nCode mbdk is " + books.get("mbdk"));
Resulting output
mbdk: Moby Dick wooz: Wizard of Oz wuth: Wuthering Heights Code mbdk is Moby Dick