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

HashMap in Java - what kind of map is this?

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 often used. The more common options are “dictionary”, “map”, or (most often) - 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.

Difference Map from other data structures

Previously, we looked at data structures where elements are stored on their own. In an array, or ArrayList / LinkedList , we store a certain number of elements. But what if our task changes slightly? 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. Basically, it's not that hard. For example, you can fit both into a string, and create a list of strings 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 of information storage, it will be problematic. And secondly, nothing will stop 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 comes to the rescue and its declared features (storing data for a pair in the “key” - “value” format). Let's take a look at the most common Map implementation, the HashMap Java class .HashMap - what kind of map is this?  - 1

Creating a HashMap in Java and working with the class

This implementation is created very simply:
public static void main(String[] args) {

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

}
Here we have created a dictionary in which the 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 - values ​​( String). Why exactly? First, a key in a HashMap is always unique . For us, this is great because we can use the passport number as a key and avoid repetitions. And the line with the full name will act as a value (the full name of different people can easily be repeated, there is nothing wrong with that for us).

Adding a new pair to 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);

   }

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

Features of HashMap Keys

Now let's check if the keys are really unique? Let's try to add a new element with the 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} As you can see, the previous element with key 162348 has been overwritten. “Key” was called the key for a reason. Values ​​in HashMap are accessed by key (but not vice versa - the key cannot be obtained by value, because values ​​can be repeated). 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 remove a pair from the dictionary, we must pass to the methods get()exactly remove()the unique key corresponding to this value. There are no numbered indexes, as in arrays or lists, in HashMap - the value is accessed by key. Console output: Lidia A. Bublikova {212133=Lydia A. Bublikova, 8082771=Donald John Trump}

Checking for the existence of a key and value

In the ArrayList and LinkedList classes , we could check if 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 some 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 handy 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 retrieved into a 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 ​​\u200b\u200bin the usual ArrayList. Console output: Keys: [212133, 8082771, 162348] Values: [Lidiya Arkadievna Bublikova, Donald John Trump, Ivan Mikhailovich Serebryakov] Thesize() and methods clear()do exactly the same as in the previous structures that we went through: the first one returns a number elements in the dictionary at the moment, the second - removes 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 Arkadievna Bublikova, 8082771=Donald John Trump, 162348=Ivan Mikhailovich Serebryakov} Now we will only output to the console after a preliminary check :)

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=Aleksey Andreevich Ermakov, 212133=Lidiya Arkadievna Bublikova, 8082771=Donald John Trump, 925648=Maxim Olegovich Arkharov, 162348=Ivan Mikhailovich Serebryakov} All elements of passportsAndNames2 have been copied to passportsAndNames . Now let's look at a more complicated example. Namely, iterating over HashMap in a loop.
for (Map.Entry entry: passportsAndNames.entrySet()) {

   System.out.println(entry);

}
An interface Map.Entrydesignates just a key-value pair within 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 the pairs, and not separately the keys or values). Conclusion: 212133=Lydia Arkadyevna Bublikova 8082771=Donald John Trump 162348=Ivan Mikhailovich Serebryakov Save this article for the future: https://habr.com/en/post/128017/ Now it is too early to read it, but in the future, when you will get a hand in using HashMap, it will help you figure out how this data structure is arranged 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