Data

Map

Java

 

Defining Map

Java 8
Map<String, Integer> map = new HashMap<>();

HashMap is a hash table.

  • It stores key/value pairs.
  • It is an implementation of the Map interface.

HashMap and Map should be imported first to be used:

import java.util.Map;
import java.util.HashMap;
 

Getting Key

Java 8
Map<String, Integer> map = new HashMap<>();

map.put("one", 1);
map.put("two", 2);

int one = map.get("one");   // 1

The get() method returns a value associated with a key.

 

Setting Key/Value

Java 8
Map<String, Integer> map = new HashMap<>();

map.put("one", 1);  // map -> {"one":1}
map.put("two", 2);  // map -> {"one":1, "two":2}

The put() method sets a key or updates an existing key with a new value.

 

Length

Java 8
Map<String, Integer> map = new HashMap<>();

map.put("one", 1);
map.put("two", 2);

int length = map.size();  // 2

The size() method returns the number of keys set in a Map.

 

Deleting Key

Java 8
Map<String, Integer> map = new HashMap<>();

map.put("one", 1);
map.put("two", 2);

map.remove("one");  // map -> {"two": 2}

The remove() method deletes a key (and its value) from a Map.

 

Listing Keys

Java 8
Map<String, Integer> map = new HashMap<>();

map.put("one", 1);
map.put("two", 2);

Set<String> keys = map.keySet();
// keys -> ["one", "two"]

The keySet() method returns a Set of keys that exist in a Map.

Set should be imported first to be used:

import java.util.Set;
 

Listing Values

Java 8
Map<String, Integer> map = new HashMap<>();

map.put("one", 1);
map.put("two", 2);

Collection<Integer> values = map.values();
// values -> [1, 2]

The values() method returns a Collection of values that exist in a Map.

The Collection package should be imported first, for the code sample here to work:

import java.util.Collection;