Java HashMap Tutorial

beginner
16 min

Java HashMap Tutorial

Welcome to the Java HashMap tutorial! šŸŽ‰ In this lesson, we'll dive into the world of collections and learn about the HashMap data structure. We'll cover the basics, real-world applications, and advanced examples to help you master this essential Java tool.

Let's kick things off! šŸŽÆ

What is a HashMap?

A HashMap is a data structure that stores key-value pairs. It's a popular choice for implementing a dictionary or associative array in Java. The HashMap allows you to store data in a more organized and efficient way compared to traditional arrays.

šŸ’” Pro Tip: The HashMap is implemented using a hash table under the hood, which makes it faster to access values using their associated keys.

Creating a HashMap

To create a new HashMap, you can use the HashMap constructor:

java
import java.util.HashMap; HashMap<String, Integer> myHashMap = new HashMap<>();

In this example, we've created a HashMap called myHashMap that stores String keys and Integer values.

Adding Key-Value Pairs

To add key-value pairs to a HashMap, you can use the put() method:

java
myHashMap.put("Apple", 100); myHashMap.put("Banana", 50);

You can also add key-value pairs while creating the HashMap:

java
HashMap<String, Integer> myHashMap = new HashMap() {{ put("Apple", 100); put("Banana", 50); }};

Accessing Values

To access the value associated with a key, you can use the get() method:

java
int bananaQuantity = myHashMap.get("Banana");

Removing Key-Value Pairs

To remove a key-value pair, you can use the remove() method:

java
myHashMap.remove("Apple");

HashMap Methods

The HashMap class provides several useful methods for managing key-value pairs, such as:

  • containsKey(Object key): Check if the HashMap contains a specific key.
  • containsValue(Object value): Check if the HashMap contains a specific value.
  • isEmpty(): Check if the HashMap is empty.
  • size(): Get the number of key-value pairs in the HashMap.

HashMap Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `HashMap` in Java?

Let's move on to some practical examples! šŸ“

Example 1: Student Grades

Let's create a HashMap to store student grades:

java
HashMap<String, Integer> studentGrades = new HashMap<>(); studentGrades.put("John", 95); studentGrades.put("Mike", 85); studentGrades.put("Emma", 80);

Now, we can calculate the average grade by looping through the HashMap:

java
int totalGrades = 0; int count = 0; for (Integer grade : studentGrades.values()) { totalGrades += grade; count++; } double averageGrade = (double) totalGrades / count;

Example 2: Shopping Cart

Next, let's create a HashMap to simulate a shopping cart:

java
HashMap<String, Integer> shoppingCart = new HashMap<>(); shoppingCart.put("Apples", 5); shoppingCart.put("Bananas", 3); shoppingCart.put("Oranges", 2);

Now, let's calculate the total cost of the items:

java
int appleCost = 1.50; int bananaCost = 0.50; int orangeCost = 1.00; int totalCost = 0; for (Integer quantity : shoppingCart.values()) { String item = shoppingCart.keySet().stream().findFirst().get(); if (item.equals("Apples")) { totalCost += appleCost * quantity; } else if (item.equals("Bananas")) { totalCost += bananaCost * quantity; } else if (item.equals("Oranges")) { totalCost += orangeCost * quantity; } }

That's it for our comprehensive Java HashMap tutorial! You now have the knowledge to work with key-value pairs using the HashMap data structure. Practice using HashMap in various scenarios to strengthen your understanding and become a proficient Java developer.

Happy coding! šŸ’»šŸ„³