Lesson 32 of 34

HashMap: Key-Value Storage

10 min 35 XP

A HashMap stores a value for each key, like a dictionary, and finds a value by its key very fast. Keys are unique: putting the same key again replaces its value.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Counting things is the classic HashMap use: map.put(w, map.getOrDefault(w, 0) + 1). If you need the keys in sorted order, use a TreeMap.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Challenge

+35 XP

Read a lowercase word and print the first character that appears only once. If there is none, print -1. Input: swiss → Output: w

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.