Lists Review and Performance : 03/31/2023
Linked Lists : 03/30/2023
Algorithms and Lists : 03/29/2023
Lambda Expressions : 03/24/2023
Anonymous Classes : 03/23/2023
Practice with Interfaces : 03/22/2023
Implementing Interfaces : 03/21/2023
Using Interfaces : 03/20/2023
Working with Exceptions : 03/10/2023
Throwing Exceptions : 03/09/2023
Catching Exceptions : 03/08/2023
References and Polymorphism : 03/07/2023
References : 03/06/2023
Data Modeling 2 : 03/03/2023
Equality and Object Copying : 03/02/2023
Polymorphism : 03/01/2023
Inheritance : 02/28/2023
Data Modeling 1 : 02/27/2023
Static : 02/24/2023
Encapsulation : 02/23/2023
Constructors : 02/22/2023
Objects, Continued : 02/21/2023
Introduction to Objects : 02/20/2023
Compilation and Type Inference : 02/17/2023
Practice with Collections : 02/16/2023
Maps and Sets : 02/15/2023
Lists and Type Parameters : 02/14/2023
Imports and Libraries : 02/13/2023
Multidimensional Arrays : 02/10/2023
Practice with Strings : 02/09/2023
null : 02/08/2023
Algorithms and Strings : 02/07/2023
Strings : 02/06/2023
Functions and Algorithms : 02/03/2023
Practice with Functions : 02/02/2023
More About Functions : 02/01/2023
Errors and Debugging : 01/31/2023
Functions : 01/30/2023
Practice with Loops and Algorithms : 01/27/2023
Algorithms : 01/26/2023
Loops : 01/25/2023
Arrays : 01/24/2023
Compound Conditionals : 01/23/2023
Conditional Expressions and Statements : 01/20/2023
Operations on Variables : 01/19/2023
Variables and Types : 01/18/2023
Welcome to CS 124 : 01/17/2023
Maps and Sets
import java.util.Map;
import java.util.HashMap;
Map<String, Integer> scores = new HashMap<>();
scores.put("you@illinois.edu", 100);
scores.put("me@illinois.edu", 100);
System.out.println(scores);
This lesson introduces two new extremely useful data structures: maps and sets.
Together, maps and lists can be used to solve almost any problem.
And sets have their uses as well.
So let’s get started!
Maps represent a fundamentally new data structure for us to consider.
So far we’ve looked at data structures that put items in order—like arrays and lists.
We’ve also discussed using higher-dimensional arrays when needed to represent higher-dimensional data.
Maps are quite different.
They don’t put items in order.
Rather, they allow us to store and look up mappings between one thing and other.
More specifically, maps store mappings between keys and values.
Each key in a map maps to just one value.
However, the same value can be mapped to by multiple keys.
Let’s make this more concrete by looking at a few examples.
In Java, to create a map we’ll import java.util.Map
and java.util.HashMap
, similarly to how we imported java.util.List
and java.util.ArrayList
when working with lists:
import java.util.Map;
import java.util.HashMap;
Map<String, String> map = new HashMap<>();
Note that, like List
s, Java Map
s also utilize type parameters within the angle brackets: <String, String>
in the example above.
However, Map
s require two type parameters: one for the key, and a second for the value.
Also note that we use the diamond operator <>
on the right, since the type parameters for the HashMap
are the same as for the Map
.
Don’t worry too much about the hash in HashMap
yet, although we’ll return to this later!
The map we created above can be used to map String
s to other String
s:
import java.util.Map;
import java.util.HashMap;
Map<String, String> map = new HashMap<>();
map.put("challen", "Geoffrey Challen");
map.put("colleenl", "Colleen Lewis");
System.out.println(map);
map.put("challen", "Geoff Challen");
System.out.println(map);
We can add mappings to our Map
using put
, which accepts a key as the first parameter and a value as the second parameter.
We also show how a second call to put
replaces the mapping for “challen”, since each key in the map maps to a single value.
Note that a map can have multiple keys that map to the same value:
import java.util.Map;
import java.util.HashMap;
Map<String, String> map = new HashMap<>();
map.put("student1", "A Student");
map.put("student2", "A Student");
System.out.println(map);
To retrieve values from a Map
we use the get
method, which accepts a single parameter: the key to look up in the Map
.
import java.util.Map;
import java.util.HashMap;
Map<String, String> map = new HashMap<>();
map.put("challen", "Geoff Challen");
map.put("colleenl", "Colleen Lewis");
System.out.println(map.get("challen"));
System.out.println(map.get("student1"));
get
returns the value mapped to by that key, or null
if that key does not exist in the Map
.
Sometimes we also refer to this as looking up the key in the map: so looking up the mapping for “challen” or “student1” in the example above.
Maps are great for solving problems where we need to save and look up information based on a key.
Let’s look at an example that may hit close to home: Recording scores on a homework problem!
import java.util.Map;
import java.util.HashMap;
String scores = """
you@illinois.edu,0
you@illinois.edu,9
me@illinois.edu,0
you@illinois.edu,10
you@illinois.edu,1
me@illinois.edu,1
me@illinois.edu,0
you@illinois.edu,0""";
Map<String, Integer> computeScores(String input) {
Map<String, Integer> map = new HashMap<>();
for (String line : input.split("\n")) {
String[] parts = line.split(",");
String email = parts[0];
int score = Integer.parseInt(parts[1]);
System.out.println(email + "->" + score);
}
return null;
If you want to iterate over all of the mappings in a Java Map
, there are a few different ways to do that:
import java.util.Map;
import java.util.HashMap;
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(4, "four");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
for (int key : map.keySet()) {
System.out.println(key);
System.out.println(map.get(key));
}
Before we wrap up, let’s briefly examine one other potentially-useful data structure: sets.
A set represents an unordered collection of distinct elements.
We can add and remove items from a set, but the set either contains the item or does not.
Items in a set don’t have an index and are not counted.
import java.util.Set;
import java.util.HashSet;
Set<Integer> set = new HashSet<>();
set.add(1);
System.out.println(set);
set.add(1);
System.out.println(set);
set.add(2);
System.out.println(set);
System.out.println(set.contains(2));
for (Integer item : set) {
System.out.println(item);
}
set.remove(1);
Sets are generally less useful that lists or maps.
But they do come in hand sometimes, particularly when you need to record membership but don’t care about counts or ordering.
Let’s look at an example where a set might come in handy:
import java.util.Set;
import java.util.HashSet;
String attendance = """
Kermit,
Gaffer,
Gonzo,
gonzo,
Gonzo,
Scooter,
Waldorf,
GONZO,
Fozzie,
Gaffer""";
More Practice
Need more practice? Head over to the practice page.