How to work with Java Map Interface

In the tutorial, JavaSampleApproach will guide you how to work with Java Map Interface, includes concept & operators.

I. Concepts for Java Map Interface

Java provides a Map Collection interface for storage data as key-value format. Java classes implement java.util.Map interface:
– java.util.HashMap
– java.util.Hashtable
– java.util.EnumMap
– java.util.IdentityHashMap
– java.util.LinkedHashMap
– java.util.Properties
– java.util.TreeMap
– java.util.WeakHashMap

Map provides 2 constructors: no arguments constructor to create a empty map, and a constructor with a single Map argument to create a new map with the same key-value mappings as its argument.
Example:

Map provides put operator to insert a new data and get operator to retrieve a value by a key.

Example:

Map interface supports a putAll method to copy all of the mappings from the specified map to this map.
Example:

Map also provides supported methods: containsKey, containsValue, clear, or isEmpty.
containsKey: used to check a key is existed in a Map.
containsValue: used to check a value is stored in a Map.
clear: used to remove all mapping.
isEmpty: used to check a map does not contain any mapping.

We can iterate a Map use entrySet method or Java 8 with Lamda expression.
Example:

II. Practice

Full SampleCode:

Output:

III. Sourcecode

MapTutorial


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*