HashMaps in Java

Hash maps are used to store key-value pairs. Similar to dictionaries, maps, objects, and tuples in other languages.

//creating a HashMap object
HashMap<Key_DataType, Value_DataType> hashMapName = new HashMap<Key_DataType, Value_DataType>();

//adding values to the hash map
hashMapName.put(key, value);

//getting value from key
keyValue = hashMapName.get(key);


The hash map class has built-in methods for iterating, key checking, and returning an entire set.

It is equivalent to a dictionary in Python, or an object in JavaScript.

The key and value datatypes specified during instantiation can only be Generics (for example, you must use the Integer generic type and not the primitive int).

public HashMap<String, Integer> grades = new HashMap<String, Integer>();
grades.put("Paul", 70);
grades.put("Adam", 85);

System.out.println(grades.get("Paul")); //will get the value associated with Paul, 70

See Also

HashMap Class - JavaDocs

Add to Slack

< Arrays   |   HashSets >

© 2019 SyntaxDB. All Rights Reserved.