Create A Hash Map

A hash map is an object used in Java to search and store values. The hash map object has a key-value pair that is saved in a variable similar to an array. A hash map can be created, filled and the values changed to create advanced search functions in websites or desktop applications.


1. Instantiate the hashmap class. A class needs to be instantiated so you can use its properties and methods in the code. The following syntax instantiates the class:

Map myhashmap = new HashMap();

2. Sort the hash map. Although this step is not necessary, it helps when displaying results. It sorts the content so users view content in alphabetical order. The following creates an instance of the “treemap” class and assigns it to the variable created in step one.

myhashmap= new TreeMap();

3. Add a value. The following code is an example of add key-value pairs to the hash map.

myhashmap.put(“key1”, new Integer(9));

myhashmap.put(“key2”, new Integer(8));

4. Replace a value. By adding a value to the hash map that already exists, the value is replaced. The following replaces “key1” with a new value:

myhashmap.put(“key1”, new Integer(10));

5. Delete a value. The hash map class also allows you to remove a value from the list. The following removes “key1” from the hash map:


READ  Teach 2d Art