Java HashMap get key value pair set

Introduction

To get key value pair set from HashMap in Java

// Get a set of the entries.
Set<Map.Entry<String, Double>> set = hm.entrySet();

// Display the set.
for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
}
    // ww w.  j av a2  s  . c  o m
    

Full source


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Main {
  public static void main(String args[]) {
    // Create a hash map.
    HashMap<String, Double> hm = new HashMap<String, Double>();

    // Put elements to the map
    hm.put("CSS", new Double(1234.34));
    hm.put("Java", new Double(123.22));
    hm.put("Javascript", new Double(1234.00));
    hm.put("HTML", new Double(99.22));
    hm.put("SQL", new Double(-19.08));

    // Get a set of the entries.
    Set<Map.Entry<String, Double>> set = hm.entrySet();

    // Display the set.
    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }//from  ww  w .  j a v a  2  s. c  om

    System.out.println();

    // Deposit 1000 into HTML's account.
    double balance = hm.get("HTML");
    hm.put("HTML", balance + 1000);

    System.out.println("HTML's new balance: " + hm.get("HTML"));
  }
}



PreviousNext

Related