Java Hashtable iterate using Iterator

Description

Java Hashtable iterate using Iterator

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class Main {
  public static void main(String args[]) {
    Hashtable<String, Double> balance = new Hashtable<String, Double>();

    String str;/*from   w w w . j a v  a  2  s .  c  om*/
    double bal;

    balance.put("HTML", 1234.12);
    balance.put("CSS", 4321.12);
    balance.put("Java", 42.12);
    balance.put("Javascript", 99.22);
    balance.put("SQL", -19.08);

    // Show all balances in hash table.
    // First, get a set view of the keys.
    Set<String> set = balance.keySet();

    // Get an iterator.
    Iterator<String> itr = set.iterator();
    while (itr.hasNext()) {
      str = itr.next();
      System.out.println(str + ": " + balance.get(str));
    }

    System.out.println();

    // Deposit 1,000 into HTML's account.
    bal = balance.get("HTML");
    balance.put("HTML", bal + 1000);
    System.out.println("HTML's new balance: " + balance.get("HTML"));
  }
}



PreviousNext

Related