← Java from Scratch
Lesson 72 of 88 · 10 XP
Set
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Set<E> is a set: each element appears no more than once.
Set<String> tags = new HashSet<>();
tags.add("rpg");
tags.add("rpg"); // false — it's already there, nothing changed
tags.contains("rpg") // true — fast, O(1) for a HashSet
tags.size() // 1
Set<Integer> s = Set.of(1, 2, 3); // immutable
Set operations go through the methods of Collection: the union addAll, the intersection retainAll,
the difference removeAll.
The three implementations differ in their iteration order: HashSet — unpredictable, LinkedHashSet — the order
of insertion, TreeSet — sorted.
Task. Read words. Print the number of all the words, the number of distinct words, and yes if some word
appeared again, otherwise no (use the fact that add returns false).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.