- Learn
- Computer Science & IT
- Programming
- Object-Oriented Programming with Java
- HashMaps and Collections in Java
HashMaps and Collections in Java
HashMap, count and group values, and keep unique values with HashSet. See what the List, Set and Map interfaces promise, sort lists and give your own classes a natural order with Comparable, and choose the collection that fits each task.BeginnerLesson 7 of 11 in Object-Oriented Programming with Java Course
What you will learn
- Create hash maps, add, read, update and remove key–value pairs, loop over a map's contents, and use your own classes as keys that the map can find again.
- Create a HashMap and put, get, update and remove entriesDeclare a HashMap with its key and value types, store pairs with put, read them with get, and handle keys that are missing.
- Loop over keys, values and entriesGo through every pair in a map with keySet, values and entrySet, know what order to expect, and change a map safely while looping.
- Use your own objects as map keysMake objects of your own classes work as keys by overriding equals and hashCode together, and keep keys unchanged while they are in a map.
- Create a HashMap and put, get, update and remove entries
- Use maps to count how often things occur, collect related values under one key, and build lookup tables that find objects quickly.
- Count occurrences and add up totals per keyBuild frequency tables and running totals with the getOrDefault pattern, and read the results correctly.
- Group values under one key with lists and sets as valuesBuild maps whose values are lists or sets, add items to the right group, and avoid the errors that lose or break groups.
- Look up objects and prices quickly with a map indexUse maps as lookup tables and indexes that find objects by a unique key, keep them inside a class, and keep several indexes consistent.
- Count occurrences and add up totals per key
- Use HashSet to store values without duplicates, test membership quickly, and combine sets with union, intersection and difference.
- Store unique values and test membership with HashSetAdd, check and remove values in a HashSet, use the result of add, and remove duplicates from a list.
- Combine sets and keep them in orderCompute unions, intersections and differences without damaging the original sets, compare sets, and pick an ordered set when order matters.
- Store unique values and test membership with HashSet
- Declare collections by their interface types, know what each interface promises, and use the shared methods that work across implementations.
- Declare variables and parameters with interface typesExplain what an interface type is, declare collections as List, Set or Map, and write methods that accept any implementation.
- Know what List, Set and Map guaranteeCompare the promises of the three interfaces, recognize their main implementations, and work with unmodifiable collections made with of.
- Declare variables and parameters with interface types
- Sort lists in natural order, give your own classes a natural order by implementing Comparable, and use that order in sorted sets and maps.
- Sort lists of numbers and stringsSort a list in place with Collections.sort, predict the order of strings, and sort in reverse or ignoring case.
- Implement Comparable in your own classGive a class a natural order by implementing Comparable and writing compareTo with safe comparisons of numbers and strings.
- Break ties and use sorted sets and mapsOrder objects by several fields, keep compareTo consistent with equals, and use TreeSet and TreeMap to keep data sorted.
- Sort lists of numbers and strings
- Compare how fast common operations are in each collection and pick the type that fits what the program has to do with its data.
- Compare the cost of common collection operationsEstimate how the time of lookups, inserts and removals grows with the size of each collection, and spot slow patterns.
- Pick a collection that fits the taskAnswer a few questions about order, duplicates and lookup to choose between arrays, lists, sets and maps, and combine them for more complex data.
- Compare the cost of common collection operations
HashMaps and Collections in Java study guide
1Store and look up data by key with HashMap
A product code can lead straight to a stock quantity, without searching a list. Maps make that link explicit, but using them well also means handling missing keys, visiting pairs safely, and defining when two key objects count as equal. Start with a small stock map, then follow how its contents change and how Java finds a stored key again. The same equality rules will matter when you use sets.
1.1 Create a HashMap and put, get, update and remove entries
A map stores a link from each key to one value. In a stock map, a product name is the key and its quantity is the value. Two products can have the same quantity, but one product key cannot hold two separate entries.
Create the map
import java.util.HashMap;
HashMap<String, Integer> stock = new HashMap<>();
The first type, String, describes keys. The second, Integer, describes values. The diamond <> on the right lets Java infer those types. Type arguments must be reference types: use Integer, Double, Character, or Boolean instead of int, double, char, or boolean. Java boxes a plain int when it stores it as an Integer, and unboxes an Integer when an int is needed.
Follow each change
stock.put("apple", 12);
stock.put("pear", 7);
Integer previous = stock.put("apple", 15);
The first call creates apple=12; the second adds pear=7. The third finds the existing "apple" key and replaces its value. The map now has two entries, and previous holds 12. A put for a key with no previous mapping returns null.
stock.get("apple") now returns 15. stock.remove("pear") returns 7 and removes that entry. Removing "pear" again returns null. size() counts entries, isEmpty() tests whether there are none, and clear() removes every entry.
Handle a missing key
stock.get("kiwi") returns null, and stock.containsKey("kiwi") returns false. This statement compiles but fails when it runs:
int quantity = stock.get("kiwi");
Java tries to unbox null into an int, causing a NullPointerException. For a map of non-null quantities, use a default:
int quantity = stock.getOrDefault("kiwi", 0);
This gives 0 without adding "kiwi" to the map. You can also check containsKey before reading. containsValue(15) asks whether any entry has that value; it may scan all values, so it is different from finding a known key.
A HashMap also permits a null key and null values. If a key is explicitly mapped to null, getOrDefault returns that stored null, not the default. containsKey distinguishes that case from a missing key. Quantity maps are simpler when every stored quantity is a real number.
Match keys and values correctly
String keys are case-sensitive: "apple", "Apple", and "apple " are different. Apply the same cleanup before storing and searching, such as name.trim().toLowerCase(). Cleaning only a search key cannot fix inconsistent stored keys.
Compare boxed values by content with equals. If two entries each hold 1000, their Integer references can differ, so == can be false even though their numeric contents match. After checking that both values are non-null, a.equals(b) compares their contents.
Key Takeaways
- Each unique key maps to one value; values may repeat.
putreplaces an existing value and returns the previous value.- A missing
getreturnsnull; unboxing it causes aNullPointerException. getOrDefaultsupplies a default only for an absent key.- Match string keys consistently and compare boxed values by content.
1.2 Loop over keys, values and entries
A map can answer a single lookup or supply all its data to a loop. Choose the view that gives the pieces the loop needs. The views are connected to the map, so changes through them can change the map too.
Choose keys, values, or entries
Use keySet() to visit keys. A lookup inside that loop can recover each value:
for (String name : phoneBook.keySet()) {
System.out.println(name + ": " + phoneBook.get(name));
}
Use values() when keys are irrelevant. For stock quantities apple 15, pear 7, and fig 3:
int total = 0;
for (int quantity : stock.values()) {
total += quantity;
}
The total becomes 25. Repeated values are still separate contributions: a values view is not a set.
An entry holds a key and its value together. Import java.util.Map and use Map.Entry<K, V> with getKey() and getValue(). This avoids a second lookup:
String best = null;
int bestScore = Integer.MIN_VALUE;
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
if (best == null || entry.getValue() > bestScore) {
best = entry.getKey();
bestScore = entry.getValue();
}
}
For Ana 82, Ben 91, and Cai 77, the result is Ben with 91. The best == null test also handles a first score equal to the smallest possible int. An empty map leaves best as null.
Make order an explicit choice
A HashMap promises no iteration order. Insertion order, sorted order, or today's printed order cannot be assumed. A LinkedHashMap preserves insertion order; a TreeMap visits sorted keys. If two scores tie, the loop above keeps the first one visited. With a HashMap, either tied name could win. Add an explicit tie rule when the result must be predictable.
Remove entries through the iterator
Calling stock.remove(key) inside a for-each loop over stock.keySet() changes the keys behind the loop. It can cause a ConcurrentModificationException. Detection is best effort; an exception-free run does not make that pattern valid.
Use the iterator's own removal method:
Iterator<Map.Entry<String, Integer>> it =
stock.entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue() == 0) {
it.remove();
}
}
Import java.util.Iterator. For apple 15, pear 0, fig 0, and kiwi 4, this removes pear and fig. Another safe approach records keys in a list, finishes the loop, then removes those keys.
Replacing an existing value does not add or remove a key. During an entry loop, entry.setValue(entry.getValue() * 2) can double the quantities safely. Do not add new keys through the map during that loop.
Separate a view from a copy
stock.keySet().remove("apple") removes the corresponding map entry. A separate list made with new ArrayList<>(stock.keySet()) is a copy of the current keys. Sorting that list does not reorder the map, and removing a name from the list does not remove its mapping.
Key Takeaways
- Use
keySet,values, orentrySetaccording to what the loop needs. HashMaphas no guaranteed iteration order; resolve ties explicitly.- Use an iterator’s
removeto delete during traversal. - Replacing an existing value is allowed during traversal.
- Map views are linked; a copied key list is separate.
1.3 Use your own objects as map keys
A product ID stored as a String already has useful equality rules. A key made from your own class needs a decision: do two separate objects with the same data represent the same key?
Hash codes narrow the search; equality confirms it
A HashMap uses hashCode() to help locate a key and equals() to check a match. Equal keys must have equal hash codes. Different keys can share a hash code; equality still tells them apart. Standard value classes such as String and Integer already follow this contract.
Without overrides, a class inherits identity-based equality from Object. Two separately created points with coordinates 2 and 3 are different keys even though their fields match:
labels.put(new Point(2, 3), "door");
String label = labels.get(new Point(2, 3));
With identity equality, label is null. The lookup created a second object, not the object used for insertion.
Override the pair together
Here a point's coordinates define its content:
import java.util.Objects;
final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Point)) {
return false;
}
Point point = (Point) other;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
The identity check handles the same object quickly. The type check rejects null and unrelated objects. The final comparison checks both coordinates. Objects.hash(x, y) builds the hash code from those same fields. With this class, the lookup above returns "door".
Overriding only equals leaves inherited hashing that does not promise equal hash codes for separate objects with equal fields. A map can then miss an equal key. A constant hash code would preserve correctness, but make searching slow. Generating both overrides in an editor helps avoid mismatched fields.
Use the exact method signature
public boolean equals(Point other) overloads the method; it does not replace equals(Object). Map lookup uses equals(Object), so the new overload does not give the map content equality. The @Override annotation makes a wrong signature a compiler error instead of a hidden lookup bug.
Keep key identity stable
Do not change fields that determine a key's equality or hash code while it is stored. If a stored point changes from (2, 3) to (5, 3), the map may no longer find it under either value even though size() is unchanged. Remove it before changing it, then insert it again. Making key fields final, as above, prevents this mistake.
These rules also determine membership in a HashSet. An ArrayList uses equals for content searches such as contains; it does not need hash codes for that search.
Key Takeaways
- Equal objects must have equal hash codes; unequal objects may share one.
- Override
equals(Object)andhashCode()with matching fields. @Overridecatches a mistakenequalsoverload.- Keep equality and hash-code fields unchanged while a key is stored.
2Count, group and index data with maps
A map can build useful information as a program reads data: a count for each word, a list for each course, or an object for each ID. The important choice is what one value represents. A number accumulates a result; a list or set collects a group; an object reference gives an index. Trace each update from an empty map so that first occurrences, repeated keys, and shared objects all have clear behavior.
2.1 Count occurrences and add up totals per key
A frequency table has one key for each distinct item and a number showing how often it occurs. The first occurrence starts a count; every later occurrence updates that same entry.
Build a count one item at a time
HashMap<String, Integer> counts = new HashMap<>();
for (String word : text.split(" ")) {
int oldCount = counts.getOrDefault(word, 0);
counts.put(word, oldCount + 1);
}
For the text "the cat saw the dog and the cat ran", the first "the" is missing, so its old count is 0 and its new count is 1. Its next two appearances change that entry to 2 and then 3. "cat" finishes at 2; "saw", "dog", "and", and "ran" finish at 1 each.
There are 6 distinct words, so counts.size() is 6. The values add to 9, the number of word occurrences. These measure different things: the map's size is not the length of the original sequence.
The update can be written on one line:
counts.put(word, counts.getOrDefault(word, 0) + 1);
A longer equivalent checks containsKey, increments an existing count, and stores 1 for a new key. All stored counts in this pattern are non-null.
Preserve the old result
Calling counts.put(word, 1) for every word repeatedly overwrites each count with 1. It records that a word exists but loses its frequency. Calling counts.get(word) + 1 without handling the first occurrence tries to unbox null and fails. The default belongs in the read step; the increased count must then be stored back.
Decide what counts as the same item
String equality is exact. "The" and "the" are different keys, as are "cat" and "cat,". If the task treats those as the same word, clean each token before counting it. Lowercase text and remove the punctuation the program treats as separators. Use one consistent rule so that results do not depend on which spelling appeared first.
The key can also be a character. With HashMap<Character, Integer>, a loop over "banana".toCharArray() produces a=3, n=2, and b=1 using the same read-increase-store pattern.
Accumulate amounts instead of occurrences
For category totals, add the current amount instead of 1:
HashMap<String, Double> totals = new HashMap<>();
double oldTotal = totals.getOrDefault(category, 0.0);
totals.put(category, oldTotal + amount);
Food 12.50, transport 3.20, and food 7.25 give food 19.75 and transport 3.20. The default is 0.0, matching the Double value type. The map still has one entry per category, however many amounts contributed.
Read the completed table
Loop over entries to find the largest count or total, remembering the best key and value. Specify a tie rule if needed. For an alphabetical report, new TreeMap<>(counts) copies the mappings into sorted key order. The count values stay unchanged; sorting the keys does not sort categories by their totals.
Key Takeaways
- A frequency map stores one count per distinct key.
- Read the old count with a zero default, add one, and store the result.
- Map size counts distinct items; the sum of counts measures occurrences.
- Normalize text consistently before counting.
- Use the same update pattern to add amounts per key.
- Choose report order separately from the accumulated values.
2.2 Group values under one key with lists and sets as values
A map value can be a collection. When several students belong to one course, the course is a key and the associated list holds all its students. The map's unique-key rule still applies: the list is the one value for that course.
Create a group before adding to it
HashMap<Character, ArrayList<String>> groups = new HashMap<>();
for (String fruit : fruits) {
char letter = fruit.charAt(0);
if (!groups.containsKey(letter)) {
groups.put(letter, new ArrayList<>());
}
groups.get(letter).add(fruit);
}
For "apple", "banana", "avocado", "cherry", and "blueberry", the first fruit creates the list for a and adds "apple". "Banana" creates the list for b. "Avocado" finds the existing a list and appends to it. The result is a → [apple, avocado], b → [banana, blueberry], and c → [cherry]. Each list keeps its own insertion order even though the HashMap does not order its keys.
The check can be shortened:
groups.putIfAbsent(letter, new ArrayList<>());
groups.get(letter).add(fruit);
putIfAbsent keeps an existing non-null list. The following get returns that list, ready for the addition.
Keep the list you have already built
An unconditional groups.put(letter, new ArrayList<>()) inside the loop replaces the old list on every occurrence. Only the last fruit for each letter survives after the next add. The opposite error is skipping creation entirely: groups.get(letter).add(fruit) throws a NullPointerException for a new key because no list exists yet.
Understand the reference
get returns the stored list reference. Adding to it changes that same list, so there is no need to put it back. This also explains a sharing bug:
ArrayList<String> shared = new ArrayList<>();
courses.put("Art", shared);
courses.put("Music", shared);
courses.get("Art").add("Jin");
Both keys now lead to [Jin]. Two keys did not create two lists. Make a fresh list for each new group when the groups should be independent.
Choose lists or sets within groups
A list preserves repeated additions. A set prevents duplicates within that group. A HashMap<String, HashSet<String>> can therefore collect each student's distinct course memberships without counting the same student twice in one course. The set rule applies inside each value; the outer map still has one entry per course.
For a read of a possibly missing group, check containsKey or use groups.getOrDefault(letter, new ArrayList<>()). An absent key then yields an empty list for that call. The default list is not automatically inserted; adding to it does not create a stored group.
Removing a group's last item leaves the key mapped to an empty collection. If the program should stop listing empty groups, check isEmpty() and remove that key too. Count groups with the outer map's size and items with the inner collections' sizes.
Key Takeaways
- Ensure a group exists, then add to its stored list or set.
- Create a fresh collection for each independent group.
getreturns the stored reference, so inner changes need no extraput.- List values keep repetitions; set values keep distinct group members.
- An empty stored group still has a map entry.
2.3 Look up objects and prices quickly with a map index
An index maps an identifying key to an object. A library can find a book by ISBN without scanning every book in a list. A lookup table uses the same shape to connect a code to a simple value, such as a product price.
Choose an identifying key
A HashMap<String, Book> can map an ISBN to its book. Each lookup needs only the key. A person's name is often a poor unique key: storing another person called "Sam Lee" under that same string replaces the previous person. Use a unique ID, or use a grouping map if one name is meant to lead to several people.
Keep an index inside the class responsible for the data:
class Library {
private HashMap<String, Book> byIsbn;
Library() {
byIsbn = new HashMap<>();
}
void addBook(Book book) {
byIsbn.put(book.getIsbn(), book);
}
Book findByIsbn(String isbn) {
return byIsbn.get(isbn);
}
}
Here Book supplies a getIsbn() method. Callers use addBook and findByIsbn; they do not need to know which map implementation is stored. The private field also gives the class one place to maintain its rules about adding and replacing books.
Check a missing result
If findByIsbn returns null, no book was found. Test the result before calling a method on it:
Book found = library.findByIsbn("978-0-00-000000-2");
if (found != null) {
found.setOnLoan(true);
}
Calling setOnLoan directly on a missing result would throw a NullPointerException. A method such as hasBook(isbn) is another way to let callers test for a key.
Follow shared objects across indexes
A map stores an object reference, not a new copy of that object. If the same book is in an all-books list, an ISBN map, and an author grouping, setOnLoan(true) changes the one book that all three refer to. This avoids three separate book objects drifting apart.
The collection structures themselves still need maintenance. Removing a book from the ISBN map does not remove its reference from an author's list. If a library keeps both indexes, its add and remove methods must update both. Centralizing those changes in methods such as addBook and removeBook helps keep searches consistent.
Use a table in a calculation
Suppose a price table has coffee 2.50, tea 2.00, and muffin 3.25. For two coffees and one muffin:
double cost = 2 * prices.get("coffee") + prices.get("muffin");
The coffee subtotal is 5.00; adding 3.25 gives 8.25. The keys identify products, and the values supply the amounts. A missing product needs an explicit decision before calculation: a zero default would silently treat it as free. The same lookup technique can therefore need a different missing-key rule from a frequency table.
Key Takeaways
- An index finds objects by an identifying key.
- Use a unique key or group multiple matching objects explicitly.
- Indexes share object references, but additions and removals must update each index.
- Keep data maps private and expose methods that maintain their rules.
3Keep unique values with sets
Sometimes the question is simply whether a value has appeared before. Sets fit that question directly and can also compare groups of values, such as people attending two events. Their lack of duplicate elements changes both the code you write and what the final size means. Work with membership first, then combine sets and choose whether their values should appear in insertion order or sorted order.
3.1 Store unique values and test membership with HashSet
A set holds each value at most once. It suits questions such as "Has this value appeared before?" or "How many different values occur?" A HashSet gives fast average membership checks without promising a display order.
Add and check values
import java.util.HashSet;
HashSet<String> visited = new HashSet<>();
boolean first = visited.add("Oslo");
boolean second = visited.add("Lima");
boolean third = visited.add("Oslo");
visited.add("Pune");
The three stored booleans are true, true, and false. The second "Oslo" matches an existing element, so it is not added. The set's size is 3. A duplicate addition does not replace a numbered slot because a set has no index.
visited.contains("Lima") returns true. visited.remove("Lima") removes it and returns true; repeating that removal returns false. Use a for-each loop to visit values. There is no get(0) for the first value of a HashSet.
Remove duplicates from a list
ArrayList<Integer> values = new ArrayList<>();
values.add(3);
values.add(1);
values.add(3);
values.add(2);
values.add(1);
HashSet<Integer> distinct = new HashSet<>(values);
The set has three values: {1, 2, 3}. Its actual iteration order is unspecified. The source list still has five elements because the constructor creates a separate collection.
Use new LinkedHashSet<>(values) to keep first-occurrence order, giving 3, 1, 2. Use new TreeSet<>(values) to obtain sorted values, 1, 2, 3. Sets are written with curly braces here to emphasize membership; Java's standard set toString() uses square brackets.
Detect the first repetition
The result of add can do the membership test and insertion together:
HashSet<Integer> seen = new HashSet<>();
for (int number : numbers) {
if (!seen.add(number)) {
System.out.println(number);
break;
}
}
For [4, 7, 2, 7, 4], the loop prints 7. It is the first value encountered for a second time, even though 4 appeared earlier in the sequence. Before 7 repeats, the set contains 4, 7, and 2. The failed insertion triggers the stop.
Know what a set cannot tell you
Checking contains before every add is unnecessary because add already handles duplicates. A list plus a contains check can also keep values unique, but each list search may scan all the stored elements. A HashSet expresses the rule directly.
Equality matters for your own objects. A HashSet<Point> needs content-based equals and a matching hashCode to merge separately created points with equal coordinates. Without those overrides, separate instances remain separate elements.
Finally, size() measures distinct values, not occurrences. The nine words in "the cat saw the dog and the cat ran" produce six distinct words. A set no longer tells you that "the" occurred three times; use a frequency map when those counts matter.
Key Takeaways
HashSetstores unique values with no index or guaranteed order.addreturns false when an equal value is already present.- A copied set removes duplicates without changing the source list.
- Use the result of
addto detect a repeated value. - Set size counts distinct values; frequencies need a map.
3.2 Combine sets and keep them in order
Sets can describe groups and compare their membership. If two event lists contain the same person several times, a set first reduces each list to the people who attended. Set operations then answer questions about either event, both events, or only one.
Combine two groups
Let Monday be {Ana, Ben, Cai, Dee} and Tuesday be {Ben, Dee, Eva}.
| Question | Method on a copy of Monday | Result |
|---|---|---|
| Who attended either day? | addAll(tuesday) | {Ana, Ben, Cai, Dee, Eva} |
| Who attended both days? | retainAll(tuesday) | {Ben, Dee} |
| Who attended Monday only? | removeAll(tuesday) | {Ana, Cai} |
These operations are union, intersection, and difference. They change the receiving set and return a boolean saying whether it changed. They do not return a new result set.
Preserve the original
Make a copy before changing membership if Monday is still needed:
HashSet<String> both = new HashSet<>(monday);
both.retainAll(tuesday);
both starts with all four Monday names. retainAll removes Ana and Cai because Tuesday lacks them. Monday itself remains unchanged. To find Tuesday only, start with a copy of Tuesday and remove Monday's names, giving {Eva}. Difference has a direction; reversing it changes the question.
Check subsets and equality
monday.containsAll(group) asks whether every value in group is present on Monday. For {Ben, Dee}, it returns true: that group is a subset of Monday. It does not require Monday to contain only those two people.
Two sets are equal when their elements match, regardless of insertion order or implementation. A HashSet containing "x" and "y" equals a TreeSet containing "y" and "x". Membership decides set equality, so order alone cannot make them unequal.
Choose an order for traversal
| Implementation | Order when visiting elements |
|---|---|
HashSet | No guarantee |
LinkedHashSet | Insertion order |
TreeSet | Sorted order |
All three avoid duplicates. Use LinkedHashSet when the first time each name appeared matters. Use TreeSet when each traversal should already be sorted. For strings, natural sorting follows character codes: lowercase and uppercase forms do not behave like a single case-insensitive alphabet.
A TreeSet with its default constructor needs elements that have a natural comparison, such as strings, numbers, or objects implementing Comparable. In that set, a comparison result of zero marks a duplicate. A class that supplies no natural comparison causes a ClassCastException when inserted. Supplying an explicit comparator is another way to define a tree collection's order; the default examples use natural order.
Key Takeaways
addAll,retainAll, andremoveAllmutate the receiving set.- Copy a set first when its original membership is still needed.
containsAllchecks a subset; set equality ignores order.- Choose hash, linked, or tree implementations for unspecified, insertion, or sorted order.
4Program with the List, Set and Map interfaces
The type on the left of a collection declaration tells the rest of the program what operations it can use. The class on the right supplies those operations and may promise a particular order. Learning to read both sides makes collection code easier to change and methods easier to reuse. It also helps explain why a list, a set, and a map behave differently even when they contain similar-looking data.
4.1 Declare variables and parameters with interface types
An interface describes operations that an implementing class provides. It lets a variable describe what code needs while leaving the storage choice to a concrete class. List, Set, and Map are collection-related interfaces in java.util.
Read the two sides of a declaration
List<String> names = new ArrayList<>();
Set<String> tags = new HashSet<>();
Map<String, Integer> counts = new HashMap<>();
The left side declares the variable's type. The right side creates an object of a class that implements it. Import both types, such as java.util.List and java.util.ArrayList. You cannot write new List<>() or new Map<>(): an interface is not a concrete object to construct.
Code using counts can call put, get, and entrySet because Map declares them. If alphabetical keys become useful, change the construction to new TreeMap<>(). Existing calls still compile. Their order can change because implementations may make different order promises; the interface does not make them identical in every behavior.
Accept the capability a method needs
A method that only counts long words can accept a Collection:
static int countLong(Collection<String> words, int min) {
int count = 0;
for (String word : words) {
if (word.length() >= min) {
count++;
}
}
return count;
}
For ["a", "tree", "house"] and a minimum of 4, it returns 2. The same method can receive an ArrayList, a LinkedList, a HashSet, or List.of(...) because it only reads the elements. A set may have already removed duplicates, so it can supply different input data from a list.
Using an interface parameter avoids requiring one particular storage class when the method does not need it. If positions are necessary, accept List. If key lookup is necessary, accept Map.
Know the limits of the declared type
List<String> names = new ArrayList<>();
names.ensureCapacity(100); // does not compile
The object is an ArrayList, but List does not declare ensureCapacity. The compiler checks the variable's declared type. Use a concrete class type when its special operation is actually needed; do not change ordinary list parameters merely to match one caller's class.
Place Map beside Collection
List and Set extend Collection, which describes a group of elements. It declares methods such as add, remove, contains, size, isEmpty, addAll, and clear. Whether a mutation is supported depends on the actual collection.
Map does not extend Collection. It stores associations and supplies views that are collections: keySet() is a Set, values() is a Collection, and entrySet() is a Set of entries. Pass counts.values() to a method needing a collection of values, not counts itself.
A class can implement several interfaces. LinkedList implements both List and Deque, a double-ended queue interface. Your own class names its promised interfaces after implements, as in class Member implements Comparable<Member>.
Key Takeaways
- Declare the needed interface on the left and construct an implementing class on the right.
- Interface parameters accept different implementations with the needed operations.
- A variable exposes only methods declared by its type.
ListandSetextendCollection;Mapsupplies collection views.
4.2 Know what List, Set and Map guarantee
Choose an interface by the rules your data needs. Similar-looking contents do not make a list, a set, and a map interchangeable: each gives different meaning to positions, repetition, and equality.
Compare the promises
| Interface | What it stores | Important rule |
|---|---|---|
List | Elements in positions starting at 0 | Repeated elements are allowed |
Set | Distinct elements | No indexed get operation |
Map | Key–value pairs | Keys are unique; values may repeat |
ArrayList and LinkedList implement List. HashSet, LinkedHashSet, and TreeSet implement Set. HashMap, LinkedHashMap, and TreeMap implement Map. Hash versions promise no traversal order; linked versions preserve insertion order; tree versions maintain sorted elements or keys. Putting an existing key again in an ordinary insertion-ordered LinkedHashMap keeps that key's place.
Read integer-list removal carefully
A List<Integer> has two relevant overloads:
List<Integer> numbers = new ArrayList<>(List.of(1, 5, 7));
numbers.remove(1);
The argument 1 is an int, so Java removes index 1: the value 5. The result is [1, 7]. Starting again with [1, 5, 7], numbers.remove(Integer.valueOf(1)) selects removal by value and leaves [5, 7]. The wrapper object makes the intended overload clear.
Compare contents with the right rule
Two lists are equal when the same elements occur in the same order. An ArrayList [1, 2] equals a LinkedList [1, 2], but not a list [2, 1]. Two sets compare membership, ignoring order. Two maps compare mappings, so insertion order does not affect map equality. Their concrete classes can differ while their contents are equal under the interface's rule.
Recognize unmodifiable collections
List<String> labels = List.of("a", "b");
Set<Integer> levels = Set.of(1, 2, 3);
Map<String, Double> prices = Map.of("tea", 2.0, "coffee", 2.5);
These factories return unmodifiable collections. Attempts to add, remove, replace, or sort their contents throw UnsupportedOperationException. Map.of accepts up to ten key–value pairs.
All three reject null elements, keys, or values with NullPointerException. Set.of rejects duplicate elements and Map.of rejects duplicate keys with IllegalArgumentException. List.of allows duplicates because a list may repeat an element. The set and map factory results have unspecified iteration order.
Copy when changes are needed
new ArrayList<>(labels) creates a modifiable list with the same elements. new HashSet<>(someList) and new HashMap<>(someMap) likewise create separate collection structures.
These copies are shallow: they hold the same element references. Removing an element from a copy leaves the original structure intact, but changing a mutable object through either collection changes the shared object. An unmodifiable collection prevents edits to its structure; it does not freeze every object stored inside it.
Key Takeaways
- Lists have positions and duplicates; sets have distinct elements; maps have unique keys.
remove(1)on an integer list removes an index;remove(Integer.valueOf(1))removes a value.- List equality checks order; set and map equality check contents without insertion order.
offactories are unmodifiable and reject nulls.Set.ofrejects duplicate elements;Map.ofrejects duplicate keys.- A modifiable copy separates collection structure but shares element references.
5Sort collections with Comparable
Sorting puts values into an order that other code can use. Numbers and strings already know their natural order; objects of your own classes need an explicit rule. Follow a list through a sort, then write a comparison that handles numbers, text, and ties safely. The rule matters beyond lists: a sorted set or map also uses it to decide when two elements or keys occupy the same place.
5.1 Sort lists of numbers and strings
A list keeps an order, but that order may simply reflect how values arrived. Sorting rearranges the list using a comparison rule. Java already supplies natural ordering for numbers and strings.
Sort a modifiable list in place
List<Double> values = new ArrayList<>(List.of(3.5, -1.0, 2.25));
Collections.sort(values);
Import java.util.Collections. The same list now holds [-1.0, 2.25, 3.5]. The sort returns void, so values = Collections.sort(values) does not compile. values.sort(null) also sorts in natural order. For an array, use Arrays.sort(array); an array containing 5, 2, and 8 becomes 2, 5, 8.
Predict string order character by character
String comparison examines the first differing character. If one string is a prefix of another, the shorter comes first. Thus "apple" precedes "apples".
The list ["pear", "Banana", "apple", "10", "9"] sorts to ["10", "9", "Banana", "apple", "pear"]. For these characters, digits precede uppercase letters and uppercase precedes lowercase. "10" precedes "9" because '1' comes before '9'; string order does not interpret digit strings as whole numbers. Store numeric data as numbers when numeric order is needed.
Use ready-made alternative orders
names.sort(String.CASE_INSENSITIVE_ORDER);
values.sort(Collections.reverseOrder());
The first call orders ["pear", "Banana", "apple"] as ["apple", "Banana", "pear"] without changing the stored capitalization. The second uses descending natural order. Numbers 4, 9, and 1 become 9, 4, and 1. These arguments are comparators, objects that supply an alternative order.
Collections.reverse(list) only reverses the current sequence. It produces descending order if that sequence was already sorted ascending; it does not sort an arbitrary list by itself.
Keep ties stable
List sorting is stable: elements that compare as equal retain their previous relative order. If a score-only comparison ties two people, their earlier order in the list remains. Stability preserves that input order; it does not invent an alphabetical tie-breaker.
Recognize failures and shortcuts
A list from List.of(...) cannot be sorted in place. Copy it to an ArrayList first. For a class without Comparable, Collections.sort(list) fails its type check at compilation. Calling list.sort(null) on such objects fails at run time with ClassCastException when comparison is needed.
Collections.max(collection) and Collections.min(collection) find the largest and smallest natural-order elements without rearranging the collection. They throw NoSuchElementException for an empty collection.
For sorted map keys, either copy map.keySet() to an ArrayList and sort the copy, or use a TreeMap. Sorting a copied key list leaves the map's own iteration order unchanged.
Key Takeaways
Collections.sortchanges a modifiable list in place and returnsvoid.- String natural order compares characters, not numeric values in text.
- Use ready-made comparators for reverse or case-insensitive order.
- Stable sorting preserves the earlier relative order of tied elements.
- Copy an unmodifiable list before sorting it.
minandmaxfind extremes without sorting.
5.2 Implement Comparable in your own class
Java cannot guess whether a member should come first by name, height, or another field. Implement Comparable to give the class one natural ordering. Sorting code can then ask each object to compare itself with another object of that class.
Write the comparison method
class Member implements Comparable<Member> {
private String name;
private int height;
Member(String name, int height) {
this.name = name;
this.height = height;
}
@Override
public int compareTo(Member other) {
return Integer.compare(this.height, other.height);
}
}
Height is measured in centimeters. Comparable<Member> specifies that the other object is a Member; no cast is needed. public int compareTo(Member other) is the required method. The standard Comparable interface is in java.lang, so no import is needed for it.
For a.compareTo(b), a negative result places a before b, zero puts them at the same comparison position, and a positive result places a after b. Only the sign matters: -35 is just as valid a negative result as -1.
Follow the order
With the height comparison, Ana 172, Ben 165, and Cai 180 sort to Ben 165, Ana 172, and Cai 180. To put taller members first, swap the arguments:
return Integer.compare(other.height, this.height);
Change the rule deliberately. Reversing the arguments reverses that field's direction; it does not change what height means or alter any member's data.
Compare whole numeric values safely
Subtraction looks convenient but can return the wrong sign when an int overflows. For -2,000,000,000 and 2,000,000,000, subtracting the second from the first wraps to 294,967,296, a positive result. Integer.compare correctly returns a negative result.
For decimal fields, use Double.compare(this.price, other.price). Casting a difference to int loses information: (int) (1.8 - 1.5) is 0, so unequal prices become a comparison tie. A comparison helper preserves the ordering without truncating the difference.
Compare text and reuse the rule
For name order, return this.name.compareTo(other.name). It follows the string's character order. compareToIgnoreCase supplies case-insensitive text comparison when that is the intended field rule.
Once a class defines natural order, operations such as Collections.sort, Collections.max, and default TreeSet or TreeMap comparisons can use it. A class can implement other interfaces as well, separated by commas after implements.
There is one natural order for the class, not a different compareTo selected for every list. Use separate comparator objects when one context needs name order and another needs height order. A height-only comparison also ties all equal heights; deciding whether that tie is acceptable becomes especially important in sorted sets.
Key Takeaways
- Implement
Comparable<YourClass>with a publiccompareTomethod. - Negative, zero, and positive results mean before, tied, and after.
- Use
Integer.compareandDouble.comparefor safe numeric ordering. - Swap comparison arguments to reverse a field’s direction.
- One class has one natural order; comparators supply other orders.
5.3 Break ties and use sorted sets and maps
A primary comparison often leaves ties. Two films may share a year, or two players may share a score. A tie-breaker gives the next field a turn only when the earlier fields compare as equal.
Compare fields in priority order
@Override
public int compareTo(Film other) {
int byYear = Integer.compare(this.year, other.year);
if (byYear != 0) {
return byYear;
}
return this.title.compareTo(other.title);
}
Year is the main rule. Title matters only when years tie. Up (2009), Avatar (2009), and Alien (1979) sort to Alien (1979), Avatar (2009), Up (2009). Comparing titles first would give them priority over year and answer a different sorting task.
Directions can differ by field. For points highest first and names A to Z, start with Integer.compare(other.points, this.points). On zero, return this.name.compareTo(other.name). Reversing the whole final list would reverse names within tied scores too.
Understand a sorted set's duplicate rule
A default TreeSet<Member> uses natural comparison both to order elements and to decide when an element is already present. If Member.compareTo uses only height, Ana 172 and Dee 172 compare as zero. Adding Ana returns true; adding Dee returns false. Ana remains the stored element even if equals considers the two members different.
A list can retain both tied objects; a tree set gives them one comparison position. Add the necessary tie-breaker if they must be distinct in the set.
Align comparison with equality
An order is consistent with equals when comparison returns zero if and only if equals returns true. For a class whose equality uses height and name, comparing height then name can meet this rule. If equality uses a different identity, such as a member ID, adding a name tie-breaker alone does not establish consistency.
The comparison must also behave like a proper order. If a comes before b, the reverse comparison must put b after a. If a is before b and b before c, a must be before c. Using whole-field comparison helpers in a fixed priority order supports these rules. An inconsistent method can misorder results or cause a sort to throw IllegalArgumentException.
Keep map keys sorted too
A TreeMap sorts keys, not values. For the word counts of "the cat saw the dog and the cat ran", the first key is "and" and the last is "the". firstKey() and lastKey() provide those extremes. Declare a TreeMap or an appropriate sorted-map interface when calling methods that plain Map does not declare.
Its key comparison also defines matching keys. A second key that compares as zero updates the existing mapping, even when equals distinguishes the objects. Default tree collections require naturally comparable elements or keys; inserting an object with no suitable comparison throws ClassCastException. An explicitly supplied comparator can define another order.
Key Takeaways
- Compare the primary field first and consult later fields only on a tie.
- Reverse only the fields that need descending order.
- Tree collections treat comparison zero as the same element or key.
- Consistency with
equalsrequires comparison zero exactly when equality is true. TreeMapsorts keys; its endpoint methods return extreme keys.- A comparison must reverse signs consistently and preserve order across triples.
6Choose the right collection for a task
A collection choice starts with the questions the program must answer: by position, by membership, or by a separate key. Order and duplicates narrow the choice further. Once the data fits the task, compare how the frequent operations grow as more values arrive. A small change, such as making one set before a loop, can remove repeated searches without making the program harder to read.
6.1 Compare the cost of common collection operations
The cost of an operation describes how its work grows with the number of stored elements. It helps identify code that is quick for a small example but slow when the collection becomes large.
Compare growth, not seconds
Constant time, O(1), stays roughly independent of collection size. Linear time, O(n), can grow in proportion to the number of elements. Logarithmic time, O(log n), grows slowly as the size increases. These labels describe growth, not exact running times on a particular computer.
| Collection | Operation | Cost |
|---|---|---|
ArrayList | get(i), set(i, x) | Constant |
ArrayList | Append at the end | Constant on average |
ArrayList | contains, indexOf, remove by value | Linear |
ArrayList | Insert or remove near the front | Linear |
HashMap / HashSet | Basic key lookup or membership, insert, remove | Constant on average with well-spread hashes |
TreeMap / TreeSet | Basic lookup, insert, remove | Logarithmic |
LinkedList | Add or remove at either end | Constant |
LinkedList | get(i) in general | Linear |
An ArrayList search may check every element; front edits shift later elements. A LinkedList must walk to a position, so repeated indexed access can be expensive. ArrayList is a useful default for ordinary list work.
Spot the repeated scan
Suppose a program checks 10,000 names against a list containing 100,000 names. Calling list.contains(name) for each name can require up to 1,000,000,000 equality checks. A fast-looking method call is still a full search when used this way.
Build a membership set once:
Set<String> allowed = new HashSet<>(allowedNames);
int matches = 0;
for (String name : incomingNames) {
if (allowed.contains(name)) {
matches++;
}
}
There is work to build the 100,000-element set, followed by 10,000 average constant-time membership checks. Counting both stages, the total grows roughly with the sum of the two input sizes, instead of their product. Rebuilding the set inside the loop would repeat the setup work and lose that benefit.
Read average guarantees correctly
Hash-based operations rely on keys whose hash codes spread values well. Returning one constant hash code for every object can still satisfy equality correctness, but makes lookup slow. It is not a free way to avoid writing a useful hash method.
Tree collections maintain sorted order with logarithmic basic operations. Doubling the number of elements adds only a small amount of search work. For 100,000 elements, a base-two logarithm is about 16.6; this suggests the scale of the search, not an exact guarantee of 17 comparisons in every Java tree lookup.
Account for the whole task
Building an extra set costs time and memory. For a few elements or one lookup, the original list may be enough. For repeated membership checks, one reusable set often removes the main cost. Start with required behavior, then inspect the operations repeated most often.
Key Takeaways
- Growth labels describe scaling, not a measured number of seconds.
ArrayListgives quick indexed access but linear searches and front edits.- Hash lookups are constant on average with suitable hash codes; tree lookups are logarithmic.
- Build a membership set once to replace repeated list scans.
- Include setup time and memory when comparing whole solutions.
6.2 Pick a collection that fits the task
The right collection keeps the information the program needs and makes its main questions easy to express. Decide the data's rules before choosing a familiar class name.
Ask what identifies an item
| Main need | Starting choice | Example |
|---|---|---|
| Find a value by a separate key | Map | Product code to price |
| Test membership without duplicates | Set | Taken usernames |
| Keep positions, order, or repeated items | List | A playlist that repeats songs |
| Keep a fixed number of slots | Array | Twelve monthly rainfall measurements |
A double[12] can hold rainfall in millimeters when each slot has a known month. A map keyed only by positions 0, 1, 2, and so on adds a layer that a list or array already supplies.
Choose the order you need
For maps and sets, use HashMap or HashSet when no order is required, LinkedHashMap or LinkedHashSet for insertion order, and TreeMap or TreeSet for sorted keys or elements. For a general-purpose list, start with ArrayList.
Word counts printed alphabetically fit a TreeMap<String, Integer>. A first-seen list of distinct tags fits LinkedHashSet<String>. Repeated songs need a list even if the songs are also stored elsewhere in a set: discarding repeats would change the playlist.
Combine collections when the data has layers
Students per course can be Map<String, List<String>>; each value is an ordered list of enrollments. Tags per article can be Map<String, Set<String>>; each article gets distinct tags. A leaderboard can be a List<Player> sorted by the player's natural comparison.
The outer and inner choices answer different questions. If courses must be listed alphabetically and students kept in enrollment order, use a TreeMap outside and a list inside. Sorting the keys does not sort the lists. If duplicate enrollment records should be ignored, use a set for the inner groups instead.
Keep related data together
Two parallel lists, one for names and one for phone numbers, rely on matching positions. Removing a name without its number breaks every later pairing. If names uniquely identify people, a map can hold the association. If names repeat or several fields belong to one person, keep person objects in a list or index them by a unique ID.
Searching a list by a field over and over is another signal to consider an index map. Keep the list too if display order and repeated entries matter, but maintain both structures together when data is added or removed.
Check the element rules and the declared type
Use an interface declaration such as Map<String, Double> prices = new HashMap<>(); so callers rely on the map operations they need. Hash-based collections need meaningful equality and matching hash codes for custom keys or elements. Default tree collections need a natural comparison that distinguishes exactly the values the collection should keep. These rules are part of making the chosen collection represent the intended data.
Key Takeaways
- Choose maps for keyed lookup, sets for membership, and lists for positions or repeats.
- Arrays can hold a fixed number of slots, including primitive values.
- Choose insertion or sorted order deliberately.
- Nested collections let outer keys and inner groups follow different rules.
- Keep related fields together and maintain multiple indexes through shared methods.
- Match equality and comparison rules to the values the collection must keep.
HashMaps and Collections in Java examples
1Follow a stock map from storage to lookup
13 steps
- 1IntroductionStart with a product question
A stock program needs to answer "How many folders are available?" A map makes the product name the key and its quantity the value. Follow one map through replacement, a missing lookup, and cleanup. Then examine why a custom key can fail even when its fields look right. Each lookup depends on what Java considers the same key.
- 2ExplanationCreate one association per key
Create
HashMap<String, Integer> stock = new HashMap<>();.Stringdescribes the keys;Integerdescribes the values. The map uses reference types, sointcannot be the value type argument. Java boxes a literal such as6whenstock.put("folder", 6)stores it. The diamond on the right lets Java infer the two types. - 3ExampleReplace a quantity
Run these updates in order:
stock.put("folder", 6); stock.put("clip", 11); Integer old = stock.put("folder", 8);The last call finds the existing folder key, stores
8, and returns6intoold. There are still two keys. A map records the latest value for a key; it does not automatically add quantities or keep a history of them. - 4ChallengeRead without inserting
What are
nandstock.size()after this read? The map still has folder 8 and clip 11.int n = stock.getOrDefault("tape", 0);---reveal---
nis0, and the size stays2. The default is a result for a missing key, not an inserted entry. Reading withget("tape")instead returns null, which cannot be unboxed into anint. - 5ExplanationRead pairs together
An entry loop supplies each key and value together:
for (Map.Entry<String, Integer> e : stock.entrySet()) { System.out.println(e.getKey() + ": " + e.getValue()); }Import
java.util.Map. The loop can show both associations without a separateget. If only a total is needed, loop overstock.values()and add the quantities; repeated quantities still contribute separately. - 6Key InsightDo not infer the first entry
The output might list folder before clip or clip before folder. HashMap promises neither order. A result such as a sum is unaffected, but a "keep the first tied score" rule can depend on traversal. Choose
LinkedHashMapfor insertion order orTreeMapfor sorted keys, and give tied maxima an explicit tie rule when the winner must be predictable. - 7ExampleDelete through the traversal
Suppose folder is now 0 and clip is 11. Remove zero quantities with an iterator:
Iterator<Map.Entry<String, Integer>> it = stock.entrySet().iterator(); while (it.hasNext()) { if (it.next().getValue() == 0) { it.remove(); } }The iterator removes its current entry and continues safely. Calling
stock.removefrom a for-each traversal can instead triggerConcurrentModificationException. - 8ChallengeSeparate a key copy
Before cleanup,
keysis created withnew ArrayList<>(stock.keySet()). Ifkeys.remove("folder")is called, what happens to the stock map?---reveal---
The map keeps its folder mapping.
keysis a separate list of the keys that existed when it was copied. Removing fromstock.keySet()itself would remove the map entry, because that object is a linked view. - 9ExampleTry a custom key
Imagine
Binhas fieldsrowandcolumnand no equality overrides. Store a label usingnew Bin(3, 4), then look it up using anothernew Bin(3, 4). The lookup returns null. These are two different objects, and inheritedObject.equalsuses identity. Matching field values have not yet been made into a matching-key rule. - 10ExplanationMake equality and hashing agree
For coordinate-based bin identity, override
equals(Object other)to compare row and column, and overridehashCode()using the same fields, such asObjects.hash(row, column). Equal coordinates must produce equal hash codes. A matching hash code alone does not establish equality; the equality check still distinguishes different coordinate keys. - 11ChallengeCatch an overload
A class defines
public boolean equals(Bin other)andhashCode()from its coordinates. Why can a lookup with a separate equal-looking bin still fail?---reveal---
The parameter must be
Objectto override Java’s equality method. The Bin-parameter method is an overload, leaving inherited identity equality in place. Adding@Overrideto that wrong signature makes the compiler expose the error. - 12ChallengeRepair a changing-key design
A bin key uses row and column in both equality methods. The program changes its row while stored, then cannot find its label. How should it update the location and then remove empty labels safely during traversal?
---reveal---
Remove the mapping before changing the key, then reinsert it. For traversal cleanup, use the entry iterator’s own removal method. Stable key identity and safe traversal solve different parts of this update.
- 13RecapKeep a map update checklist
For a missing lookup, decide whether a default or an explicit absence check fits the task. For a loop, decide whether order matters and whether keys will be removed. For a custom key, check the exact
equals(Object)signature, matching hash fields, and stable identity. These checks locate different causes of the same symptom: a mapping that the program cannot use as expected.
2Build attendance information as records arrive
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn arrivals into useful answers
- 2ExampleStart a session count
- 3ExampleSeparate distinct sessions from records
- 4ChallengeRepair a reset count
- 5ExplanationCreate a group once
- 6ExampleFollow the inner reference
- 7ChallengeFind the shared-group bug
- 8ExplanationIndex by an identifying key
- 9Key InsightChange one object in several places
- 10ChallengeKeep removal consistent
- 11ChallengeCombine counts with distinct membership
- 12RecapCheck a first arrival and a repeat
3Compare two attendance groups
9 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk who, not how many visits
- 2ExampleCollapse repeated scans
- 3ChallengeStop at the first repeated arrival
- 4ExampleKeep only shared members
- 5ExplanationChoose the direction of difference
- 6ChallengeTest a selected group
- 7TipChoose a useful report order
- 8ChallengeMake a sorted missing-attendance report
- 9RecapRead the receiver as the starting group
4Read collection declarations and copies
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead both sides of the declaration
- 2ExplanationDeclare what the caller needs
- 3ExampleUse a wider parameter for reading
- 4ChallengeDiagnose the missing method
- 5ConnectionChoose the meaning of contents
- 6ExampleFollow integer removal
- 7ChallengeCopy before sorting
- 8Key InsightSeparate object edits from list edits
- 9ChallengePass the right map view
- 10RecapCheck type, operation, and object
5Build a ranking that keeps the right ties
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose what comes first
- 2ExampleSort the same list
- 3ExplanationRead the first differing character
- 4ChallengeUse a supplied order
- 5ExplanationGive a class one natural order
- 6ExampleAvoid a numeric false tie
- 7ChallengeReverse the numeric field
- 8ExampleBreak only genuine ties
- 9ExampleWork through the ranking
- 10ChallengeSee what a tree set retains
- 11Key InsightMatch ordering to identity
- 12ConnectionCheck a sorted map’s key
- 13ChallengeKeep every result in a ranked list
- 14TipMake the rule work across triples
- 15RecapCheck a comparison in two places
6Choose structures for a course roster
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionList the questions the program asks
- 2ExampleNotice the scan inside the loop
- 3ExplanationBuild membership support once
- 4ChallengeCompare growing inputs
- 5ExampleKeep repeated enrollment records
- 6ExplanationChoose outer and inner order
- 7ChallengeRepair the wrong duplicate rule
- 8TipPay for the order you need
- 9ChallengeCombine the final design
- 10RecapChoose behavior before measuring speed
HashMaps and Collections in Java practice questions
Set 1: Read and update maps reliably10 Practice Questions
Question 1 of 10
HashMap<String, Integer> receives put("brush", 5) and then put("brush", 14). What are its size and the value for "brush"?Show answerHide answer
put does not add the incoming quantity to the previous quantity. Accumulation needs a read-and-update expression.Question 2 of 10
"tray". What happens when int n = map.get("tray"); runs?Show answerHide answer
get returns null, and assigning that result to an int attempts to unbox it. Null has no primitive integer value, so Java throws NullPointerException. The map does not supply zero or create a quantity merely because the destination variable is numeric.Question 3 of 10
Show answerHide answer
entrySet() supplies an entry containing both a key and its associated value. A key loop can recover the value with another lookup, but the key-set element itself supplies only the key. The values view cannot identify which key belongs to each status.Question 4 of 10
equals method. What must their hash codes be?Show answerHide answer
Question 5 of 10
"beam" → 9. The program executes Integer old = map.put("beam", 13); and then Integer removed = map.remove("beam");. What are old, removed, and the final size?Show answerHide answer
put returns with the value it stores.Question 6 of 10
entrySet() and must delete each zero-valued entry. How should it remove the entry during traversal?Show answerHide answer
ConcurrentModificationException. Replacing a quantity with null would not delete the entry.Question 7 of 10
Cell class defines equals(Cell other) and a field-based hashCode. Separate cells with equal fields fail to match as HashMap keys. What method change addresses the equality error?Show answerHide answer
equals(Object), so the Cell-parameter method is an overload and leaves inherited identity equality in place. Override the Object-parameter method and use matching fields in hashing. Changing the hash code alone cannot make the wrong equality method participate in lookup.Question 8 of 10
Show answerHide answer
Question 9 of 10
"ink" → 4 and "paper" → 0. keys is a new ArrayList copied from its key set. The program removes "ink" from keys, removes "paper" through the map’s key-set view, then doubles all remaining map values. What is left in the map?Show answerHide answer
Question 10 of 10
Location equality and hashing use a mutable coordinate. A key is stored, then its coordinate is changed while stored; its mapping is now missed by lookup. What update sequence should the design use to prevent this failure?Show answerHide answer
Set 2: Build counts and compare groups10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
!seen.add(n). What number is reported?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
"north" → 4, "south" → 2, and "west" → 3. How many distinct keys does it contain?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"cedar". What does another add("cedar") return?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
"red", "gold", "red", "blue", "gold", "red" using counts.put(word, counts.getOrDefault(word, 0) + 1). What are the red count and map size?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
groups.put(team, new ArrayList<>()); followed by groups.get(team).add(name);. A team receives Omar, Pia, then Ren. What remains under that team?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
C.removeAll(B). What does C contain?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Device object is stored in a list and an ID map. It is retrieved from the map, then its status field changes. What status does the list’s stored reference expose?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
"Morning" and "Evening". The program adds "Lee" through Morning, then replaces Evening’s mapping with a fresh list and adds "Jo" through Evening. What are the final groups?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
retainAll(B). D is copied from B and runs removeAll(C). What are D and the result of A.containsAll(C)?Show answerHide answer
Save this lesson to see this answer.
Set 3: Diagnose collection behavior10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
"pending" explicitly mapped to null. What does getOrDefault("pending", 20) return?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Set.of("draft", "final", "draft") is evaluated?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
"Ari Chen" are inserted, and the first can no longer be retrieved by that name. What design directly preserves both for individual lookup?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Collections.reverse(list), what is its content?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
"Support". The program evaluates List<String> result = groups.getOrDefault("Support", new ArrayList<>()); and then adds "Nia" to result. A later groups.get("Support") returns what?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
ScoreKey equality uses team and points; its natural comparison uses only points. A default TreeMap gets key East-30 with value "old", West-30 with value "new", then North-18 with value "low". What are its size and the value found using East-30?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
addAll(B), then removeAll(A). What is U, and did either original change?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Combine lookup, grouping, and order10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
map.values() produce?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
get. What complete repair preserves the requirements?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Use interfaces and sort data10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Set<String> codes = new HashSet<>();, what is the declared type of codes?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
a.compareTo(b) mean?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
List<Integer> starts as [4, 8, 12]. It runs remove(1). What remains?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
"zebra", "Apron", "18", "3", "ant"?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Collection<String>. A caller has Map<String, String> labels and wants the method to process each label value. What should be passed?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
(int) (this.price - other.price). What goes wrong for prices 6.8 and 6.3?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
compareTo do next?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Ticket object. A second ArrayList is copied from it. The program changes the ticket’s label through the copy, then clears the copy. What does the original list contain?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Reading.equals uses station ID and temperature, but its natural comparison uses only temperature. A default TreeSet receives A at 16, B at 16, then C at 12. What are its size and the retained IDs?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Array
double[12] can give each month one slot for its rainfall measurement in millimeters.Autoboxing
12 into a map of Integer values automatically boxes that number for storage.C
Character order
"7", "Bee", and "ant", natural string order places the digit before the letters.Collection
Collection<String> and iterate over either a list or a set.Collection choice
Collection view
Comparable
compareTo method.Comparable<Member> so list sorting can order its instances by height.Comparator
String.CASE_INSENSITIVE_ORDER sorts a list without changing the capitalization stored in each string.compareTo
Consistency with equals
Constant time
ArrayList position does not require scanning all the earlier positions in that list.Content equality
equals(Object).D
Declared type
ArrayList stored in a List variable cannot expose ensureCapacity through that variable.Diamond syntax
HashMap<String, Integer> m = new HashMap<>();, the diamond avoids repeating the two types.Distinct item
"sun rain sun" contains two distinct word keys but records three occurrences.Duplicate arrival
add returns false.E
Encapsulation
addBook method updates them together instead of callers editing them.F
Frequency table
G
getOrDefault
Grouping
H
Hash-code contract
equals to return equal hash codes, while allowing collisions for unequal objects.x and y fields in both their equality test and their hash-code method.HashMap
HashMap<String, Integer> can look up the current count for a product without using a list position.HashSet
HashSet<String> can track names already processed while a program reads a longer input sequence.I
Identity equality
Object.Implementation
HashMap and TreeMap both implement Map, but they make different promises about key order.In-place sort
Collections.sort(values), the existing list variable exposes its elements in their new order.Index
Integer overflow
Integer.compare avoids the sign reversal that subtraction can cause.Interface
List<String> can receive an ArrayList or a LinkedList without changing its signature.Interface parameter
Map<String, Integer> while callers choose hash or tree storage.Intersection
retainAll removes unshared values from its receiver.Iteration order
Iterator
hasNext(), next(), and the iterator’s remove() to delete zero quantities.K
Key normalization
Key–value pair
"pen" → 18 connects a product name to the number currently available.Keyed lookup
L
Linear time
LinkedHashMap
LinkedHashMap.LinkedHashSet
LinkedHashSet loses repeats while keeping the order in which tags first appeared.List
Logarithmic time
Lookup table
M
Map
Map.Entry
Membership
contains using that set’s matching rule.Mutable key
N
Natural order
"20" and "3" places "20" first because the initial characters decide their order.Nested collection
O
Overload
remove(1) selects index removal while remove(Integer.valueOf(1)) selects value removal.P
Parallel lists
putIfAbsent
putIfAbsent can ensure that its key has a list without replacing an existing one.R
Running total
S
Set
Set difference
Setup cost
Shallow copy
Shared reference
Stable sort
Structural modification
Subset
a.containsAll(b) tests b within a.T
Tie-breaker
Transitivity
TreeMap
firstKey().TreeSet
Truncation
U
Unboxing
Integer lookup to an int fails because the returned null cannot be unboxed.Union
addAll forms it by changing the receiving set.Unique identifier
Unmodifiable collection
List.of must be copied before sorting, but a stored mutable object is not frozen by that list.W
Wrapper class
Integer as its value type because int cannot appear as a generic type argument.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.