Variables

HashMaps in Java

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


Syntax
//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);

Notes

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).


Example
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
Documentation

HashMap Class - JavaDocs

Add to Slack

< Arrays   |   HashSets >

© 2018 SyntaxDB. All Rights Reserved.