Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.4 Patterns — membership across two collections

Lesson

What is in one but not the other

A frequent task is comparing two collections: how many items of one are not in the other. The efficient way is to put the second collection into a set, then check each item of the first with contains. A set lookup is fast and reads clearly.


Worked example

String[] have = {"x", "y", "z", "x"};
String[] known = {"y", "z"};
Set<String> knownSet = new HashSet<String>();
for (int i = 0; i < known.length; i++) {
    knownSet.add(known[i]);
}
int missing = 0;
for (int i = 0; i < have.length; i++) {
    if (!knownSet.contains(have[i])) {   // not in the known set
        missing++;
    }
}
System.out.println(missing);   // 2 — the two x's

Every have element that is not in knownSet is counted, repeats included.


▶ Try it: run this — count the items of have missing from known.



To check membership in the second collection quickly, put it into...


!knownSet.contains(x) is true when...


Type exactly what this program prints.

import java.util.HashSet;
import java.util.Set;
public class Main { public static void main(String[] a){
    String[] have = {"a", "b", "c", "a"};
    String[] known = {"b"};
    Set<String> ks = new HashSet<String>();
    for (int i = 0; i < known.length; i++) { ks.add(known[i]); }
    int miss = 0;
    for (int i = 0; i < have.length; i++) { if (!ks.contains(have[i])) { miss++; } }
    System.out.println(miss);
}}

The two x's in have both count as missing because...


True or false?