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

1=Rahul

2=Mia

3=Priyanka

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

Output:

Key: 1 Value: Rahul

Key: 2 Value: Mia

Key: 3 Value: Priyanka

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

Key: 1 Value: Rahul

Key: 2 Value: Mia

Key: 3 Value: Priyanka

Key: 5 Value: Chaand

Key: 7 Value: Angel

Key: 10 Value: Maqbul

Priyanka

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

Key: 1 Value: Rahul

Key: 2 Value: Mia

Key: 3 Value: Priyanka

Key: 5 Value: Chaand

Key: 7 Value: Angel

Key: 10 Value: Maqbul

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 getting value and other is to getting 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 value matches then return the key.

Output

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

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu