Map
Published Apr 17, 2022Updated Apr 30, 2022
Contribute to Docs
The Map
interface is found in java.util
and it allows collections to store items as key-value pairs. It is implemented in the HashMap
and TreeMap
classes. A Map
allows its contents to be accessed as a set of keys, a set of values, or a set of key-value pairs. The data types of the keys and values are set when the Map
is declared, and each can be any data type.
Syntax
MapClass<KeyDataType,ValueDataType> myMap = new MapClass<KeyDataType,ValueDataType>
The MapClass
is a class that implements the Map
interface, and is initialized with two generic types inside angle brackets < ... >
. The generic data types for KeyDatatype
and ValueDatatype
can either be different or the same.
Methods
A Map
class will implement the following methods:
.clear()
: removes all key-value pairs from theMap
..containsKey(key)
: returnstrue
ifkey
is one of the keys in theMap
..containsValue(value)
: returnstrue
ifvalue
is one of the values in theMap
..get(key)
: returns the value of the givenkey
from theMap
..put(key,value)
: adds a key-value pair to theMap
..remove(key)
: removes the key-value pair associated withkey
from theMap
..size()
: returns anint
that represents the number of key-value pairs in theMap
.
Map
- .containsKey()
- Checks if a map contains a specified key.
- .containsValue()
- Checks if a given value is present in a map.
- .putIfAbsent()
- Adds the key-value pair to a map only if the key is not already present.
- .replaceAll()
- Replaces each value in the map with a new value returned by the applied function.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours