Home  >  Article  >  Java  >  How to print elements of HashMap in Java?

How to print elements of HashMap in Java?

PHPz
PHPzforward
2023-09-11 09:49:02938browse

How to print elements of HashMap in Java?

HashMap is a subclass of the AbstractMap class, used to store key-value pairs. Each key maps to a single value in the map, and keys are unique . This means we can only insert a key once into the map, and duplicate keys are not allowed , but the value can be mapped to multiple keys. We can add elements using the put() method of the HashMap class and iterate elements using the Iterator interface.

Syntax

public V put(K key, V value)

Example

import java.util.*;
import java.util.Map.*;
public class HashMapTest {
   public static void main(String[] args) {
      HashMap map = new HashMap();
<strong>      </strong>// adding the elements to hashmap using put() method
      map.put("1", "Adithya");
      map.put("2", "Jai");
      map.put("3", "Chaitanya");
      map.put("4", "Krishna");
      map.put("5", "Ramesh");
      if(!map.isEmpty()) {
         Iterator it = map.entrySet().iterator();
         while(it.hasNext()) {
            Map.Entry obj = (Entry)it.next();
            System.out.println(obj.getValue());
         }
      }
   }
}

Output

Adithya
Jai
Chaitanya
Krishna
Ramesh

The above is the detailed content of How to print elements of HashMap in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete