Skip to main content
← Advanced CS Study Guide

Code Scholars Tutoring · Advanced CS

5.1 Sets and Maps as Abstractions

How it works

A set stores membership without duplicates; a map stores key-to-value associations. Both are specifications, implementable by hashing or by a tree.

Choose a set when only membership matters and a map when each key carries data.

Common error

Assuming iteration order. A hash-based structure gives no ordering guarantee.

Worked example

Java snippets run inside a main method. Add import java.util.*; when collection types are used.

Java

Set<String> names = new HashSet<String>();
names.add("Ada"); names.add("Ada");
Map<String, Integer> counts = new HashMap<String, Integer>();
counts.put("Ada", 2); counts.put("Ada", 3);
System.out.println(names.size());
System.out.println(counts.get("Ada"));

Output

1
3

A set records membership without duplicates. A map associates one current value with each key; putting the same key again replaces its previous mapping.

Exercises

5.1.1 · Explain

Choose a set or a map for unique visitor identifiers and for visit counts by identifier.

Show solution

Use a set for unique membership. Use a map from identifier to count when each key needs an associated total.

5.1.2 · Write code

Count occurrences of a, b, a and print the count of a.

Show solution

Update the value for each encountered key.

One valid solution

Map<String,Integer> counts = new HashMap<String,Integer>();
for (String word : new String[]{"a","b","a"})
    counts.put(word, counts.getOrDefault(word,0)+1);
System.out.println(counts.get("a"));

Expected output

2
Open Java compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic