The Map interface of the Java collections framework provides the functionality of the map data structure.
It implements the Collection interface.
In Java, elements of Map are stored in key/value pairs. Keys are unique values associated with individual Values.
A map cannot contain duplicate keys. And, each key is associated with a single value.
Classes that implement Map:
Since Map is an interface, we cannot create objects from it.
In order to use functionalities of the Map interface, we can use these classes:
In Java, we must import the java.util.Map package in order to use Map. Once we import the package, here’s how we can create a map.
// Map implementation using HashMap Map<String, Integer> contactList = new HashMap<>();
In the above code, we have created a Map named contact list. We have used the HashMap class to implement the Map interface.
The above map contains keys as String and values as integer like contactList[“Rishabh”] maps to an integer maybe 2.
The Map interface includes all the methods of the Collection interface. It is because Collection is a super interface of Map.
Besides methods available in the Collection interface, the Map interface also includes the following methods:
To read more about maps and its methods follow this link: Click Here
LinkedHashMap in Java
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order.
Important Features of a LinkedHashMap:
You are given an examination database that consists of student’s names and their total marks. After that, you will be given some student’s name as a query. For each query, print the total marks of that student.
1 <= NumberOfStudents, NumberOfQueries <= 105
1 <= totalMarks in any entry <= 109
1 <= |nameOf Student| <= 8
The first line will have an integer A denoting the number of entries in the examination database. Each entry consists of two lines: a name and the corresponding total marks.
After these, the next line will contain an single integer Q denoting the number of queries.
The next Q lines each will contain a student’s name.
For each case, print “Not found” if the student name has no entry in the examination database. Otherwise, print the total marks of that student. See sample output for the exact format.
3 Ojas 10 Rishabh 5 Akash 15 2 Aka Ojas
Not Found 10
Query 1: Student named "Aka" is not present in our given database so we will print "Not Found" Query 2: Student named "Ojas" is present in our database so we will print the marks corresponding to it i.e 10