DEV Community

Sebastian Utoiu
Sebastian Utoiu

Posted on

4 2

Java HashMap

In this tutorial, I will present you about the Java HashMap class and its various operations with the help of examples.

The HashMap class of the Java collections' framework provides the functionality of the hash table data structure.

It stores elements in key/value pairs. Here, keys are unique identifiers used to associate each value on a map.
The HashMap class implements the Map interface.

How to Create a HashMap

In order to create a HashMap, we must import the java.util.HashMap package first. Once we import the package, here is how we can create HashMaps in Java.

// hashMap creation with 8 capacity and 0.6 load factor

HashMap<K, V> numbers = new HashMap<>();
Enter fullscreen mode Exit fullscreen mode

In the above code, we have created a hashmap named numbers. Here, K represents the key type and V represents the type of values. For example:

HashMap<String, Integer> numbers = new HashMap<>();
Enter fullscreen mode Exit fullscreen mode

Here, the type of keys is String and the type of values is Integer.

Example 1: Create HashMap in Java

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    // create a hashmap
    HashMap<String, Integer> languages = new HashMap<>();

    // add elements to hashmap
    languages.put("Java", 8);
    languages.put("JavaScript", 1);
    languages.put("Python", 3);
    System.out.println("HashMap: " + languages);
  }
}
Enter fullscreen mode Exit fullscreen mode

Output

HashMap: {Java=8, JavaScript=1, Python=3}
Enter fullscreen mode Exit fullscreen mode

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If you found this post useful, consider leaving a ❤️ or a nice comment!

Got it