Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
What is Map? | Map
Java Data Structures

What is Map?What is Map?

Finally, we've moved on to truly complex and intriguing data structures. Today, we'll discuss the Map interface in Java. The Map interface is part of the Java Collections framework and defines methods for working with data in the form of key-value pairs.

Let's take a look at the definition:

In Java, the term Map typically refers to the Map interface and its implementations, providing a data structure for storing key-value pairs. These pairs allow associating a specific value with a unique key, ensuring efficient access to the data.

The primary implementation of such a data structure in Java is HashMap, which implements the Map interface. Let's explore the main methods and the operating principles of this implementation.

We'll start with the declaration and methods:

java

main.java

Here, we see that in the generics or diamond brackets, two values are specified:

  • The value K corresponds to the data type of the key;
  • The value V corresponds to the data type of the value.

Thus, when declaring this data structure, we indicate the data types of our key-value values.

Now, let's examine the methods defined in the Map interface:

  • V put(K key, V value):
    • Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Note

In the case of using HashMap<>(), when inserting multiple values with the same key, a collision occurs. We will delve into the working principle of HashMap later in this section.

java

main.java

  • V get(Object key):
    • Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

This is where we specify the key to retrieve the corresponding value.

Let's retrieve the value with key 2:

java

main.java

  • boolean containsKey(Object key):
    • Returns true if the map contains a mapping for the specified key.
  • boolean containsValue(Object value):
    • Returns true if the map contains one or more keys mapped to the specified value.

These two methods are obviously related, and they help determine whether the specified map contains the desired keys or values. These methods are convenient to use as conditions since they return boolean values.

Let's look at an example:

java

main.java

In the example above, we check for the presence of a key and the presence of a value in the map. If values are found, we display them on the console. If there are no such values, we output messages indicating the absence of such data.

  • boolean isEmpty():
    • Returns true if this map contains no key-value mappings.
  • V remove(Object key):
    • Removes the mapping for the specified key from this map if present and returns the previous value.

Just like in other data structures, we can remove elements from the map.

Note

When using HashMap, all values under one key will be removed. We will delve into this in more detail later in this section.

java

main.java

Thus, we can remove elements by key.

Next, there are methods you are already familiar with, which I will list without examples. But there are also interesting methods left.

Let's start with the basics:

  • void clear():
    • Removes all elements from the map.
  • int size():
    • Returns the number of key-value mappings in this map.
  • void putAll(Map<? extends K, ? extends V> m):
    • Copies all of the mappings from the specified map to this map.

Now, let's move on to the methods that return a collection with values(or keys) from the map. In other words, we retrieve from the data structure a key-value structure that stores only values(or keys). For example, ArrayList<>.

java

main.java

Here, we obtained a collection of values from the map. Now, we can transfer this collection to an ArrayList:

java

main.java

We initialized an ArrayList using values from the map.

There is also a method that returns keys from the map. However, these keys will be returned in the form of a structure called a Set. We won't delve into this data structure now; it's worth mentioning that a Set is a data structure that contains exclusively unique values.

Let's look at this method:

  • Set<K> keySet():
    • Returns a Set view of the keys contained in this map.
java

main.java

Thus, we can also retrieve a set of all keys from the map.

Well, it seems we're done with the methods. Let's now take a look at the usage of the map, as well as practical examples:

Map Usage

A structure like key-value has many practical applications. Let's consider the simplest of these structures: a student grading system.

Let's create a map where the key is of type String, representing the student's name, and the value is of type Integer, representing the student's grade. This way, we can assign grades to students and easily retrieve the grade of a specific student using the key:

java

main.java

Now, let's imagine we are tasked with retrieving the grades of Mike and Alice, and then comparing them. We can easily accomplish this using the methods we have learned above. Let's implement this in the code:

java

main.java

I used the ternary operator and the compareTo() method of the Integer wrapper class. In case you don't understand how it works, it can be explained as follows:

java

main.java

Note

If you think about it, such queries are very similar to SQL queries. If you are familiar with SQL, it will be much easier for you to understand the interaction with different data structures and databases.

Now, let's consider what if we are asked to gather all students with a grade higher than 7 (excluding 7). This becomes interesting, and I will now explain to you how to do it!

Iteration through the map

Iterating over elements in a Map in Java can be done using various methods provided by the Map interface and its implementations. Here are several ways to iterate over a Map:

  • Iterating over Keys (keySet()):
    • The keySet() method returns a set of all keys in the Map. You can use this set to iterate over keys and retrieve corresponding values.
java

main.java

  • Iterating over Values (values()):
    • The values() method returns a collection of all values in the Map. You can use this collection to iterate over values.
java

main.java

  • Iterating over Key-Value Pairs (entrySet()):
    • The entrySet() method returns a set of Map.Entry objects representing key-value pairs. This allows iterating over pairs directly.
java

main.java

Let's delve a bit deeper into this. Initially, it might seem insanely complex to understand, but you don't need to get into the details of how it works, as the syntax is always the same:

Using the entry object, we can simultaneously access both the key and the value in the map. Now, let's solve the task given earlier using the entry set: retrieve all students with a grade higher than 7. For this, we'll use a check through entry.getValue(), and when we find suitable students, we'll retrieve their keys into a pre-created ArrayList:

java

main.java

Thus, we can iterate through the map and find the desired list of students who passed the exam!

The entry set is a very useful tool as it allows various ways of iterating through the map using a loop, having access to both the key and the value.

In the next chapter, we will delve into how HashMap, which we used so actively in this chapter, actually works!

1. What interface in Java represents a collection of key-value pairs?
2. How do you iterate through all keys in a `Map` using a for-each loop?
3. What is the purpose of the `values()` method in a `Map`?
4. Which method is used to check if a specific key is present in a `Map`?
5. Which method is used to remove a key-value pair from a `Map` in Java?

What interface in Java represents a collection of key-value pairs?

Selecciona la respuesta correcta

How do you iterate through all keys in a Map using a for-each loop?

Selecciona la respuesta correcta

What is the purpose of the values() method in a Map?

Selecciona la respuesta correcta

Which method is used to check if a specific key is present in a Map?

Selecciona la respuesta correcta

Which method is used to remove a key-value pair from a Map in Java?

Selecciona la respuesta correcta

¿Todo estuvo claro?

Sección 3. Capítulo 1
course content

Contenido del Curso

Java Data Structures

What is Map?What is Map?

Finally, we've moved on to truly complex and intriguing data structures. Today, we'll discuss the Map interface in Java. The Map interface is part of the Java Collections framework and defines methods for working with data in the form of key-value pairs.

Let's take a look at the definition:

In Java, the term Map typically refers to the Map interface and its implementations, providing a data structure for storing key-value pairs. These pairs allow associating a specific value with a unique key, ensuring efficient access to the data.

The primary implementation of such a data structure in Java is HashMap, which implements the Map interface. Let's explore the main methods and the operating principles of this implementation.

We'll start with the declaration and methods:

java

main.java

Here, we see that in the generics or diamond brackets, two values are specified:

  • The value K corresponds to the data type of the key;
  • The value V corresponds to the data type of the value.

Thus, when declaring this data structure, we indicate the data types of our key-value values.

Now, let's examine the methods defined in the Map interface:

  • V put(K key, V value):
    • Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Note

In the case of using HashMap<>(), when inserting multiple values with the same key, a collision occurs. We will delve into the working principle of HashMap later in this section.

java

main.java

  • V get(Object key):
    • Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

This is where we specify the key to retrieve the corresponding value.

Let's retrieve the value with key 2:

java

main.java

  • boolean containsKey(Object key):
    • Returns true if the map contains a mapping for the specified key.
  • boolean containsValue(Object value):
    • Returns true if the map contains one or more keys mapped to the specified value.

These two methods are obviously related, and they help determine whether the specified map contains the desired keys or values. These methods are convenient to use as conditions since they return boolean values.

Let's look at an example:

java

main.java

In the example above, we check for the presence of a key and the presence of a value in the map. If values are found, we display them on the console. If there are no such values, we output messages indicating the absence of such data.

  • boolean isEmpty():
    • Returns true if this map contains no key-value mappings.
  • V remove(Object key):
    • Removes the mapping for the specified key from this map if present and returns the previous value.

Just like in other data structures, we can remove elements from the map.

Note

When using HashMap, all values under one key will be removed. We will delve into this in more detail later in this section.

java

main.java

Thus, we can remove elements by key.

Next, there are methods you are already familiar with, which I will list without examples. But there are also interesting methods left.

Let's start with the basics:

  • void clear():
    • Removes all elements from the map.
  • int size():
    • Returns the number of key-value mappings in this map.
  • void putAll(Map<? extends K, ? extends V> m):
    • Copies all of the mappings from the specified map to this map.

Now, let's move on to the methods that return a collection with values(or keys) from the map. In other words, we retrieve from the data structure a key-value structure that stores only values(or keys). For example, ArrayList<>.

java

main.java

Here, we obtained a collection of values from the map. Now, we can transfer this collection to an ArrayList:

java

main.java

We initialized an ArrayList using values from the map.

There is also a method that returns keys from the map. However, these keys will be returned in the form of a structure called a Set. We won't delve into this data structure now; it's worth mentioning that a Set is a data structure that contains exclusively unique values.

Let's look at this method:

  • Set<K> keySet():
    • Returns a Set view of the keys contained in this map.
java

main.java

Thus, we can also retrieve a set of all keys from the map.

Well, it seems we're done with the methods. Let's now take a look at the usage of the map, as well as practical examples:

Map Usage

A structure like key-value has many practical applications. Let's consider the simplest of these structures: a student grading system.

Let's create a map where the key is of type String, representing the student's name, and the value is of type Integer, representing the student's grade. This way, we can assign grades to students and easily retrieve the grade of a specific student using the key:

java

main.java

Now, let's imagine we are tasked with retrieving the grades of Mike and Alice, and then comparing them. We can easily accomplish this using the methods we have learned above. Let's implement this in the code:

java

main.java

I used the ternary operator and the compareTo() method of the Integer wrapper class. In case you don't understand how it works, it can be explained as follows:

java

main.java

Note

If you think about it, such queries are very similar to SQL queries. If you are familiar with SQL, it will be much easier for you to understand the interaction with different data structures and databases.

Now, let's consider what if we are asked to gather all students with a grade higher than 7 (excluding 7). This becomes interesting, and I will now explain to you how to do it!

Iteration through the map

Iterating over elements in a Map in Java can be done using various methods provided by the Map interface and its implementations. Here are several ways to iterate over a Map:

  • Iterating over Keys (keySet()):
    • The keySet() method returns a set of all keys in the Map. You can use this set to iterate over keys and retrieve corresponding values.
java

main.java

  • Iterating over Values (values()):
    • The values() method returns a collection of all values in the Map. You can use this collection to iterate over values.
java

main.java

  • Iterating over Key-Value Pairs (entrySet()):
    • The entrySet() method returns a set of Map.Entry objects representing key-value pairs. This allows iterating over pairs directly.
java

main.java

Let's delve a bit deeper into this. Initially, it might seem insanely complex to understand, but you don't need to get into the details of how it works, as the syntax is always the same:

Using the entry object, we can simultaneously access both the key and the value in the map. Now, let's solve the task given earlier using the entry set: retrieve all students with a grade higher than 7. For this, we'll use a check through entry.getValue(), and when we find suitable students, we'll retrieve their keys into a pre-created ArrayList:

java

main.java

Thus, we can iterate through the map and find the desired list of students who passed the exam!

The entry set is a very useful tool as it allows various ways of iterating through the map using a loop, having access to both the key and the value.

In the next chapter, we will delve into how HashMap, which we used so actively in this chapter, actually works!

1. What interface in Java represents a collection of key-value pairs?
2. How do you iterate through all keys in a `Map` using a for-each loop?
3. What is the purpose of the `values()` method in a `Map`?
4. Which method is used to check if a specific key is present in a `Map`?
5. Which method is used to remove a key-value pair from a `Map` in Java?

What interface in Java represents a collection of key-value pairs?

Selecciona la respuesta correcta

How do you iterate through all keys in a Map using a for-each loop?

Selecciona la respuesta correcta

What is the purpose of the values() method in a Map?

Selecciona la respuesta correcta

Which method is used to check if a specific key is present in a Map?

Selecciona la respuesta correcta

Which method is used to remove a key-value pair from a Map in Java?

Selecciona la respuesta correcta

¿Todo estuvo claro?

Sección 3. Capítulo 1
some-alt