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.2 HashSet — removing duplicates

Lesson

A classic use: deduplicating

To find the distinct values in an array, add every element to a set and read its size() — the duplicates collapse automatically. As with HashMap, a HashSet has no guaranteed order, so use order-independent results like a count or a membership test.


Worked example

String[] words = {"a", "b", "a", "c", "b", "a"};
Set<String> unique = new HashSet<String>();
for (int i = 0; i < words.length; i++) {
    unique.add(words[i]);
}
System.out.println(unique.size());        // 3 — a, b, c
System.out.println(unique.contains("c")); // true

Six words go in; three distinct values come out.


▶ Try it: run this — the six-element array has three distinct values.



To count the distinct values in an array, you...


After adding all of {a, b, a, c, b, a} to a set, size() is...


Type exactly what this program prints.

import java.util.HashSet;
import java.util.Set;
public class Main { public static void main(String[] a){
    int[] arr = {5, 5, 6, 7, 7, 7};
    Set<Integer> u = new HashSet<Integer>();
    for (int i = 0; i < arr.length; i++) { u.add(arr[i]); }
    System.out.println(u.size());
}}

Match each collection to what it stores.


True or false?