HashMap in java

 Since Map is an interface you need to instantiate a concrete implementation of the Map interface in order to use it. The Java Collections API contains the following Map implementations:

  • java.util.HashMap
  • java.util.Hashtable
  • java.util.EnumMap
  • java.util.IdentityHashMap
  • java.util.LinkedHashMap
  • java.util.Properties
  • java.util.TreeMap
  • java.util.WeakHashMap

 


- Hashmap does not guarantee any order of its elements

TreeMap also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated -


Only Objects Can Be Inserted

Only Java objects can be used as keys and values in a Java Map. In case you pass primitive values (e.g. int, double etc.) to a Map as key or value, the primitive values will be auto-boxed before being passed as parameters. Here is an example of auto-boxing primitive parameters passed to the put() method:

map.put("key", 123);

The value passed to the put() method in the above example is a primitive int. Java auto-boxes it inside an Integer instance though, because the put() method requires an Oject instance as both key and value. Auto-boxing would also happen if you passed a primitive as key to the put() method.

Null Keys

Quite surprisingly you can use the value null as a key in a Java Map. 

You can insert only one null key in a Map.

Here is an example of using a null key in a Java Map:

Map map = new HashMap();

map.put(null, "value for null key");

To obtain the value stored by the null key you call the get() method with null as parameter value. Here is an example of getting the value for the null key of a Java Map:

Map<String, String> map = new HashMap<>();

String value = map.get(null);

Null Values

The value of a key + value pair stored in a Map is allowed to be null - so this is valid:

map.put("D", null);

Just keep in mind that you will get a null out when you call get() later with that key - so this will return null:

Object value = map.get("D");

The value variable will have the value null after this code has been executed, if a null value was inserted for this key earlier (like in the previous example).

Inserting All Elements From Another Map

The Java Map interface has a method called putAll() which can copy all key + value pairs (entries) from another Map instance into itself. In set theory, this is also referred to as the union of the two Map instances.

Here is an example of copying all entries from one Java Map into another via putAll():

Map<String, String> mapA = new HashMap<>();
mapA.put("key1", "value1");
mapA.put("key2", "value2");

Map<String, String> mapB = new HashMap<>();
mapB.putAll(mapA);

After running this code the Map referenced by variable mapB will contain both of the key + value entries inserted into mapA at the beginning of the code example.

The copying of entries only goes one way. Calling mapB.putAll(mapA) will only copy entries from mapA into mapB, not from mapB into mapA. To copy entries the other way, you would have to execute the code mapA.putAll(mapB).

Checking if Map Contains Key

You can check if a Java Map contains a specific key using the containsKey() method. Here is how that looks:

boolean hasKey = map.containsKey("123");

After running this code, the hasKey variable will have the value true if a key + value pair was inserted earlier with the String key 123, and false if no such key + value pair was inserted.

Checking if Map Contains Value

The Java Map interface also has a method that enables you to check if the Map contains a certain value. The method is called containsValue() . Here is how calling the containsValue() looks:

boolean hasValue = map.containsValue("value 1");

After executing this code the hasValue variable will contain the value true if a key + value pair was inserted ealier with the String value "value 1", and false if not.

Removing Entries From a Java Map

You remove Entries by calling the remove(Object key) method. You thus remove the (key, value) pair matching the key. Here is an example of removing the entry for a given key in a Java Map :

map.remove("key1");

After executing this instruction, the Map referenced by mapA will no longer contain an entry (key + value pair) for the key key1.

Removing All Entries

You can remove all entries in a Java Map using the clear() method. Here is how that looks:

map.clear();  

Iterating the Keys of a Java Map

There are several ways to iterate the keys stored in a Java Map. The most used methods for iterating the keys are:

  • Via the key Iterator
  • Via the for-each loop

All methods will be covered in the following sections.

Using a Key Iterator

You can iterate all the keys of a Java Map via its keySet() method. Here is how iterating the keys of a Java Map looks:

Iterator iterator = map.keySet().iterator();

while(iterator.hasNext(){
  Object key   = iterator.next();
  Object value = map.get(key);
}

As you can see, the key Iterator returns every key stored in a Java Map, one by one (one for each call to next()). Once you have the key, you can obtain the element stored for that key using the Map get() method.

In the example above, the Iterator next() method returns an Object - and so does the get() method. With generic types specified for the Map these methods would have returned the type of the key and value objects respectively. Here is how that would look:

Map<String, String> map = new HashMap<>();

Iterator<String> iterator = map.keySet().iterator();

while(iterator.hasNext(){
  String key   = iterator.next();
  String value = map.get(key);
}

Notice how a generic type is now also specified for the Iterator obtained from map.keySet().iterator().

Using a Key For-Each Loop

From Java 5 you can also use the for-each loop to iterate the keys stored in a Java Map. Here is how that looks:

for(Object key : map.keySet()) {
    Object value = map.get(key);
}

Iterating the Values of a Java Map

It is also possible to just iterate the values stored in a Java Map. You obtain a Collection of the values stored in a Map via the values() method. You can iterate the values in the Collection in following ways:

  • Using an Iterator
  • Using the for-each Loop

All of these options are covered in the following sections.

Using a Value Iterator

The first way to iterate all values stored in a Java Map is to obtain a value Iterator instance from the value Set, and iterate that. Here is how iterating the values stored in a Java Map using a value Iterator:

Map<String, String> map = new HashMap<>();

Iterator<String> iterator = map.values().iterator();

while(iterator.hasNext()) {
    String nextValue  iterator.next();
}

Since a Set is unordered, you do not have any guarantees about the order in which the values in the value set are iterated. However, if you are using a TreeSet you can control this order still.

Using a Value For-Each Loop

The second method of iterating the values stores in a Java Map is via the Java for-each loop. Here is how iterating the values of a Java Map using the for-each loop looks in code:

Map<String, String> map = new HashMap<>();

for(String value : map.values()){
    System.out.println(value);
}

Comments

Popular posts from this blog

Jenkins CICD in One Page

Why do we need a build tool?

Deutsche Bank Interview Questions - 2024