← Java from Scratch Lesson 75 of 88 · 10 XP

LinkedHashSet

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

LinkedHashSet is a HashSet plus a linked list over the elements: iteration goes in the order of insertion. The speed is almost the same as HashSet (O(1)), with slightly more memory.

Set<String> s = new LinkedHashSet<>();
s.add("c"); s.add("a"); s.add("c"); s.add("b");
System.out.println(s);      // [c, a, b] — the first appearance of each

A typical task is removing repeats while keeping the order: the history of visited pages, unique players in the order they joined.

Task. A login log: each word is a player's nickname. Print the unique nicknames in the order of their first login, then in the order of their last login (a hint: remove the nickname before adding it, then it moves to the end).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.