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

How to print elements of HashMap in Java?

PHPz
Release: 2023-09-11 09:49:02
forward
1004 people have browsed it

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)
Copy after login

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());
         }
      }
   }
}
Copy after login

Output

Adithya
Jai
Chaitanya
Krishna
Ramesh
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template