print out a hashmap code example
Example 1: how to print the map in java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Stream;
class MapUtil
{
public static void main (String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
Iterator<Integer> itr = map.keySet().iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
for (Integer key : map.keySet()) {
System.out.println(key);
}
map.keySet().iterator()
.forEachRemaining(System.out::println);
map.keySet().stream()
.forEach(System.out::println);
Stream.of(map.keySet().toArray())
.forEach(System.out::println);
System.out.println(map.keySet().toString());
Stream.of(map.keySet().toString())
.forEach(System.out::println);
}
}
Example 2: printing elemenst in hashmap
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {
public static void main(String args[]) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
String var= hmap.get(2);
System.out.println("Value at index 2 is: "+var);
hmap.remove(3);
System.out.println("Map key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
}
}