Skip to content

Latest commit

 

History

History
70 lines (52 loc) · 2.35 KB

introduction.md

File metadata and controls

70 lines (52 loc) · 2.35 KB

Introduction

A Map is a data structure for storing key value pairs. It is similar to dictionaries in other programming languages. The Map interface defines operations on a map.

Java has a number of different Map implementations. HashMap is a commonly used one.

// Make an instance
Map<String, Integer> fruitPrices = new HashMap<>();

Add entries to the map using put.

fruitPrices.put("apple", 100);
fruitPrices.put("pear", 80);
// => { "apple" => 100, "pear" => 80 }

Only one value can be associated with each key. Calling put with the same key will update the key's value.

fruitPrices.put("pear", 40);
// => { "apple" => 100, "pear" => 40 }

Use get to get the value for a key.

fruitPrices.get("apple"); // => 100

Use containsKey to see if the map contains a particular key.

fruitPrices.containsKey("apple"); // => true
fruitPrices.containsKey("orange");  // => false

Remove entries with remove.

fruitPrices.put("plum", 90);    // Add plum to map
fruitPrices.remove("plum");     // Removes plum from map

The size method returns the number of entries.

fruitPrices.size();  // Returns 2

You can use the [keys] or [values] methods to obtain the keys or the values in a Map as a Set or collection respectively.studentScores

fruitPrices.keys();    // Returns "apple" and "pear" in a set
fruitPrices.values();  // Returns 100 and 80, in a Collection