In this section we will learn about another data structure - Map . The more common options are “dictionary”, “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. Internally HashMap class uses HashTable to Implement the Map Interface. Because of it, HashMap allows to execution time for basic operations like get() and put()
In other sections, we looked at data structures where elements are stored on their own. In an array, or a list 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: “RRTutors, 1278 424242”. 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 can be constructed by any of the following ways
HashMap() |
Default constructor of HashMap |
HashMap(Map m) |
We can initialise the HashMap by passing other elements of Map object |
HashMap(int capacity) |
We can construct the HashMap with initial capacity size |
HashMap(int capacity, float fill ratio) |
This will initialise by capacity and fill ration of the HashMap using its arguments |
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).
void clear() |
This will remove all elements from HashMap |
Object clone() |
This will returns a shallow copy of the given HashMap, This method return type is “Object” |
boolean containsKey(Object key) |
This will check the HashMap the passed key is exist or not and return respected boolean value |
boolean containsValue(Object value) |
This will check the HashMap the passed value is exist or not and return respected boolean value |
Set entrySet() |
This will returns a collection of the mappings inside the Map |
Object get(Object key) |
To get the value of a specific key inside HashMap we will use this property |
boolean isEmpty() |
To check the given Map is contains any data or not |
Set keySet() |
This will returns complete keys as Set inside given Map |
Object put(Object key, Object value) |
This will add data to the Map |
Object remove(Object key) |
This property will be used to remove a specified key from the Map |
Collection values() |
Returns the all values contained inside the Map |
Int Size() |
To get the size of the Map will use Size() property |
This task looks like this:
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> passportsAndNames = new HashMap<>();
passportsAndNames.put(121212, "KIRAN RATHOD");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
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:
{
121212
=KIRAN RATHOD
, 232323
=WILLIAMSON
, 909090
=ROBINHOOD
}
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(121212, "KIRAN RATHOD");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
passportsAndNames.put(121212, "CHANDRAGUPTHA");
System.out.println(passportsAndNames);
}
Output:
{
121212
=CHANDRAGUPTHA
, 232323
=WILLIAMSON
, 909090
=ROBINHOOD
}
As you can see, the previous element with key 121212
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 the HashMap:
public static void main(String[] args) {
HashMap<Integer, String> passportsAndNames = new HashMap<>();
passportsAndNames.put(121212, "CHANDRAGUPTHA");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
String lidiaName = passportsAndNames.get(121212);
System.out.println(lidiaName);
passportsAndNames.remove(909090);
System.out.println(passportsAndNames);
}
In order to get a value, or remove a pair from the dictionary, we must pass to the methods exactly get()
the remove()
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: CHANDRAGUPTHA
{
121212
=CHANDRAGUPTHA
, 232323
=WILLIAMSON
}
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(121212, "CHANDRAGUPTHA");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
System.out.println(passportsAndNames.containsKey(121212));
System.out.println(passportsAndNames.containsValue("WILLIAMSON"));
}
Output:
TRUE
TRUE
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(121212, "CHANDRAGUPTHA");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
Set<Integer> keys = passportsAndNames.keySet();
System.out.println("Ключи: " + keys);
ArrayList<String> values = new ArrayList<>(passportsAndNames.values());
System.out.println("Значения: " + 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 usual ArrayList
.
Console output:
Keys: [121212
, 232323
, 909090
]
Values: [CHANDRAGUPTHA, WILLIAMSON,ROBINHOOD
]
Methods size()
and 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(121212, "CHANDRAGUPTHA");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
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(121212, "CHANDRAGUPTHA");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
if (!passportsAndNames.isEmpty()) {
System.out.println(passportsAndNames);
}
}
Output:
{121212
=CHANDRAGUPTHA
, 232323
=WILLIAMSON, 909090=ROBINHOOD
}
Now we will only output to the console after a preliminary check :)
You know 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(121212, "CHANDRAGUPTHA");
passportsAndNames.put(232323, "WILLIAMSON");
passportsAndNames.put(909090, "ROBINHOOD");
passportsAndNames.put(131313, "RAGUVARAN");
passportsAndNames2.put(925648, "SUNDER");
passportsAndNames.putAll(passportsAndNames2);
System.out.println(passportsAndNames);
}
Output:
{121212
=CHANDRAGUPTHA
, 232323
=WILLIAMSON, 909090=ROBINHOOD,131313=RAGUVARAN,925648=SUNDER
}
All elements of passportsAndNames2 have been copied to passportsAndNames .
Let see more complicated example. Namely, iterating over HashMap in a loop.
for (Map.Entry entry: passportsAndNames.entrySet()) {
System.out.println(entry);
}
An interface Map.Entry
designates 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).