xxxxxxxxxx
for (V valuesName : arbitraryHashMap.values()) {
//Do Stuff with valuesName
}
xxxxxxxxxx
for (Map.Entry<String,Integer> pair : myHashMap.entrySet()) {
System.out.println(pair.getKey());
System.out.println(pair.getValue());
}
xxxxxxxxxx
import java.util.HashMap;
import java.util.Map.Entry;
class Main {
public static void main(String[] args) {
// create a HashMap
HashMap<Integer, String> languages = new HashMap<>();
languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);
// iterate through keys only
System.out.print("Keys: ");
for (Integer key : languages.keySet()) {
System.out.print(key);
System.out.print(", ");
}
// iterate through values only
System.out.print("\nValues: ");
for (String value : languages.values()) {
System.out.print(value);
System.out.print(", ");
}
// iterate through key/value entries
System.out.print("\nEntries: ");
for (Entry<Integer, String> entry : languages.entrySet()) {
System.out.print(entry);
System.out.print(", ");
}
}
}
xxxxxxxxxx
// Creating a HashMap
Map<String, String> langTable = new HashMap<String, String>();
// Inserting elements to HashMap
langTable.put("A", "Angular");
langTable.put("J", "Java");
langTable.put("P", "Python");
langTable.put("H", "Hibernate");
// Iterating HashMap using foreach
for (Map.Entry<String, String> set : langTable.entrySet()) {
// Printing all elements of a Map
System.out.println(set.getKey() + " = " + set.getValue());
}
xxxxxxxxxx
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}