13.04. Maps

Maps

  • Eclipse: Oxygen
  • Java: 1.8

The maps are an interface. A map contains values based on the key, for example, key and value pair. Each pair of key and value is known as an entry. Both the key and values are objects. A map cannot contain duplicate keys, it must be unique, but the value can be duplicated.

In the following program, we use interface type(Map), generics and diamond operator to declare a new map.

Map<Integer,String> student = new HashMap<>();

Object put(Object k, Object v) method associates the specified value V with the specified key.

The Map.Entry is a key and its value combined into one class, which allows you to iterate over Map entrySet() instead of having to iterate over Map.keySet(), then get the value for each key.

Output

In the following program, keys and values are displayed separately.

Output:

The get(Object key) method will return the value associated with a specified key in this Java hashmap.

Note: HashMap does not maintain the order of its element.

Output

In the following program, we have another basic example is the retrieving value from HashMap. This is the example of looping Map and here we have used a Combination of Iterator and EntrySet to display all keys and values of a Java Map.

Output

Search under Maps

We have already studied the data structure of the Map under the Collections frameworks in Java. In maps we see the search mechanism by two methods, one is to get value and other is to get key methods.

It is easier to find any value in the map just by passing the key to get() method.

In the following program, we will see the mechanism to find the key in the map. To do that we need to iterate through the map for each value. If the value matches then return the key.

Output

The key for value "OOPS" :Code [sectionNo=S01, lectureNo=L07]

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments