Task 5 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 — the common values of two collections

Lesson

Combining sets: the intersection

To find the distinct values that appear in both collections, use two sets. Put the first collection into a set for fast membership. Then, walking the second, add each value that is in the first set to a result set — because it is a set, duplicates collapse, so its size() is the number of distinct shared values.


Worked example

String[] first = {"a", "b", "a", "c"};
String[] second = {"b", "c", "d"};
Set<String> inFirst = new HashSet<String>();
for (int i = 0; i < first.length; i++) {
    inFirst.add(first[i]);
}
Set<String> common = new HashSet<String>();
for (int i = 0; i < second.length; i++) {
    if (inFirst.contains(second[i])) {
        common.add(second[i]);   // duplicates collapse here
    }
}
System.out.println(common.size());   // 2 — b and c

Two sets working together: one answers "is it in the first?", the other collects the distinct matches.


▶ Try it: run this — count the distinct values common to both arrays.



To count distinct values common to both collections, use...


Collecting the matches in a set means...


Type exactly what this program prints.

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

Match each set to its job in the intersection.


True or false?