There are many ways to store your objects and data in Java. Interfaces such as List, Set and Map are options. The point that distinguishes the Map interface from other solutions is that it uses the key, value logic. It references a key to each value it stores. Therefore, it is easy to find a specific element. In addition, it has many useful methods in itself.

Classes using the Map Interface have the following methods:

clear: Clears all values ​​in the Map.
containsKey (Object key): Queries whether a certain key has already been entered.
containsValue (Object value): Queries whether a certain object has already been entered.
get (Object key): Returns the object corresponding to the key.
put (Object key, Object value): Records the key-value pair.
remove (Object key): Deletes the value corresponding to a certain key.
size: Returns the number of key-value binaries registered up to that time.

Classes that implement Map

Java provides several classes that implement the Map interface.

java.util.HashMap: Hash table implementation of Map interface. It is by far the best implementation of the Map interface. Provides fast search and update.

java.util.LinkedHashMap: It is a hash table and linked list implementation of the Map interface. It ensures that the insertion of elements is sequential and works almost as fast as HashMap.

java.util.TreeMap: An implementation of the SortedMap interface, it provides sequential insertion but slow in searches and updates

The HashMap class, which implements the Map interface and uses all the features in the Map interface, is frequently used in Map operations in Java.

Examples for working in key-value format using HashMap in Java are as follows:

Map<Integer,String> map = new HashMap<Integer, String>();
      map.put(1, "One");
      map.put(2, "Two");
      map.put(3, "Three");
      map.put(4, "Four");

In the example above, numbers and their spellings are recorded as key-value in a variable named map produced in HasMap class.

Later, when we want to reach information about the number, we can reach it with the following piece of code.

System.out.println(map.get(2));

The remove() function is used to delete a key with HashMap. With this function, deletion can be performed.

map.remove(2);

Navigating maps with a for loop is quite simple. The following snippet makes it easy to loop over Maps:

for(Map.Entry<Integer, String> item: map.entrySet()) {
         System.out.println(item);
}

Using the Map interface to store your objects and data according to your algorithms provides advantages in terms of speed and cost.

Leave a Reply