JavaRush /Java Blog /Random EN /HashMap in Java - what kind of map is it?

HashMap in Java - what kind of map is it?

Published in the Random EN group
Hello! Today we will talk about another data structure - Map. Its official Russian name is “associative array,” but it is not used often. The more common options are “dictionary”, “map”, or (most often) the slang anglicism “map” :) Inside Map, data is stored in the “key” - “value” format, that is, in pairs. Both keys and values ​​can be any objects—numbers, strings, or objects of other classes.

How Map differs from other data structures

Previously, we looked at data structures where elements are stored by themselves. In an array, or ArrayList / LinkedList , we store a certain number of elements. But what if our task changes a little? For example, imagine that we are faced with the task of creating a list of 100 people, where the person’s full name and passport number will be stored. In principle, it is not that difficult. For example, you can fit both in a line and create a list of lines like this: “Anna Ivanovna Reshetnikova, 4211 717171.” But this solution has two drawbacks. First, we may need a passport search function. And with this format for storing information, this will be problematic. And secondly, nothing will prevent us from creating two different people with the same passport numbers. And this is the most serious drawback of our solution. Such situations should be completely excluded; there are no two people with the same passport number. Here Map and its stated features come to our aid (storing data in a pair in the “key”-”value” format). Let's look at the most common Map implementation - the Java HashMap class .HashMap - what kind of map is this?  - 1

Creating a HashMap in Java and working with the class

This implementation is very simple to create:
public static void main(String[] args) {

   HashMap<Integer, String> passportsAndNames = new HashMap<>();

}
Here we have created a dictionary in which elements will be stored in the “number-string” format. The number will be the key, and the string will be the value. We also indicated what type of keys we will have ( Integer) and what type of values ​​( String). Why is this so? First, the key in a HashMap is always unique . This will work great for us because we can use the passport number as a key and avoid duplicates. And the line with the full name will act as a value (the full name of different people can easily be repeated, there’s nothing wrong with that for us).

Adding a new pair to a HashMap

This task looks like this:
public class Main {

   public static void main(String[] args) {
       HashMap<Integer, String> passportsAndNames = new HashMap<>();


       passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
       passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
       passportsAndNames.put(8082771, "Donald John Trump");
       System.out.println(passportsAndNames);

   }

}
The method is used for this put(). Additionally, HashMap has an overridden method toString()so it can be printed to the console. The output will look like this: {212133=Lidiya Arkadyevna Bublikova, 8082771=Donald John Trump, 162348=Ivan Mikhailovich Serebryakov}

Features of HashMap Keys

Now let's check if the keys are truly unique? Let's try to add a new element with a key already in the map:
public static void main(String[] args) {

   HashMap<Integer, String> passportsAndNames = new HashMap<>();

   passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
   passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
   passportsAndNames.put(8082771, "Donald John Trump");
   passportsAndNames.put(162348, "Viktor Mikhailovich Stychkin");//repeat key

   System.out.println(passportsAndNames);

}
Output: {212133=Lidiya Arkadyevna Bublikova, 8082771=Donald John Trump, 162348=Viktor Mikhailovich Stychkin} The previous element with key 162348, as you can see, was overwritten. “The Key” was called the key for a reason. Values ​​in a HashMap are accessed by key (but not vice versa - the key cannot be obtained by value, because values ​​can be duplicated). This is clearly seen in the examples of getting an element, as well as removing an element from a HashMap:
public static void main(String[] args) {

   HashMap<Integer, String> passportsAndNames = new HashMap<>();

   passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
   passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
   passportsAndNames.put(8082771, "Donald John Trump");

   String lidiaName = passportsAndNames.get(212133);
   System.out.println(lidiaName);


   passportsAndNames.remove(162348);
   System.out.println(passportsAndNames);

}
In order to get a value or delete a pair from the dictionary, we must pass exactly the unique key corresponding to this value to the get()methods . There are no numerical indexes, as in arrays or lists, in HashMap - the value is accessed by key. Console output: Lidiya Arkadyevna Bublikova {212133=Lidiya Arkadyevna Bublikova, 8082771=Donald John Trump}remove()

Checking for the presence of a key and value

In the ArrayList and LinkedList classes , we could check whether a list contains a particular element. HashMap also allows you to do this, and for both parts of the pair: it has methods containsKey()(checks for the presence of a key) and containsValue()(checks for the presence of a value).
public static void main(String[] args) {

   HashMap<Integer, String> passportsAndNames = new HashMap<>();

   passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
   passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
   passportsAndNames.put(8082771, "Donald John Trump");


   System.out.println(passportsAndNames.containsKey(11111));
   System.out.println(passportsAndNames.containsValue("Donald John Trump"));

}
Output: false true

Getting a list of all keys and values

Another convenient feature of HashMap is that you can separately get a list of all keys and all values . For this, methods keySet()and are used values():
public class Main {

   public static void main(String[] args) {

       HashMap<Integer, String> passportsAndNames = new HashMap<>();

       passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
       passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
       passportsAndNames.put(8082771, "Donald John Trump");

       Set<Integer> keys = passportsAndNames.keySet();
       System.out.println("Keys: " + keys);

       ArrayList<String> values = new ArrayList<>(passportsAndNames.values());
       System.out.println("Values: " + values);

   }

}
The keys are extracted into the collection Set. Its peculiarity is that it cannot contain repeating elements. Now the main thing to remember is that the list of all keys can be taken out of the HashMap into a separate collection. In the example, we saved the values ​​to normal ArrayList. Console output: Keys: [212133, 8082771, 162348] Values: [Lidiya Arkadyevna Bublikova, Donald John Trump, Ivan Mikhailovich Serebryakov] Methods size()do clear()exactly the same thing as in the previous structures that we went through: the first one returns a number elements in the dictionary at the current moment, the second one deletes all elements.
public static void main(String[] args) {

   HashMap<Integer, String> passportsAndNames = new HashMap<>();

   passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
   passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
   passportsAndNames.put(8082771, "Donald John Trump");

   System.out.println(passportsAndNames.size());
   passportsAndNames.clear();
   System.out.println(passportsAndNames);

}
Output: 3 {} To check if our HashMap has at least one element, we can use the method isEmpty():
public static void main(String[] args) {

   HashMap<Integer, String> passportsAndNames = new HashMap<>();

   passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
   passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
   passportsAndNames.put(8082771, "Donald John Trump");

   if (!passportsAndNames.isEmpty()) {

       System.out.println(passportsAndNames);

   }

}
Output: {212133=Lidiya Arkadyevna Bublikova, 8082771=Donald John Trump, 162348=Ivan Mikhailovich Serebryakov} Now we will output to the console only after preliminary verification :)

Combining two maps into one

Another interesting point is that two maps can be combined into one . There is a method for this putAll(). We call it on the first HashMap , pass the second as an argument, and the elements from the second will be added to the first:
public static void main(String[] args) {

   HashMap<Integer, String> passportsAndNames = new HashMap<>();
   HashMap<Integer, String> passportsAndNames2 = new HashMap<>();

   passportsAndNames.put(212133, "Lydia Arkadievna Bublikova");
   passportsAndNames.put(162348, "Ivan Mikhailovich Serebryakov");
   passportsAndNames.put(8082771, "Donald John Trump");

   passportsAndNames2.put(917352, "Alexey Andreevich Ermakov");
   passportsAndNames2.put(925648, "Maxim Olegovich Arkharov");


   passportsAndNames.putAll(passportsAndNames2);
   System.out.println(passportsAndNames);

}
Output: {917352=Alexey Andreevich Ermakov, 212133=Lidiya Arkadyevna Bublikova, 8082771=Donald John Trump, 925648=Maxim Olegovich Arkharov, 162348=Ivan Mikhailovich Serebryakov} All elements of passportsAndNames2 were copied to passportsAndNames . Now let's look at a more complicated example. Namely, iterate over HashMap in a loop.
for (Map.Entry entry: passportsAndNames.entrySet()) {

   System.out.println(entry);

}
An interface Map.Entryjust means a key-value pair inside a dictionary. The method entrySet()returns a list of all pairs in our HashMap (since our map consists of just such Entry pairs, we iterate over pairs, and not separately keys or values). Conclusion: 212133=Lidiya Arkadyevna Bublikova 8082771=Donald John Trump 162348=Ivan Mikhailovich Serebryakov Save this article for the future: https://habr.com/ru/post/128017/ Now it’s too early to read it, but in the future, when you will get your hands on using HashMap, it will help you understand how this data structure works from the inside. Also, don't forget to check out the official Oracle documentation on HashMap.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION