CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
Maps
Code

Code that uses a hash map

// create an empty hash map
HashMap books = 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
TreeMap books = 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
Previous | HashMap and TreeMap classes | Code | Next