Java: Unique visitors

Use sets to count distinct visitors and list them two ways.

What to build

A program that reports the distinct visitors in a log.

Requirements

  • Read n names (one per line). Names that differ only in case are the same visitor; use the lower-case form.
  • Print distinct: D, then first seen: ... (names in the order first seen, separated by spaces), then sorted: ... (alphabetical).

Input

Line 1: n. Then n names.

Output

Three lines.

Constraints

1 ≤ n ≤ 1000.

Example

Input:

5
Rina
arif
RINA
zoya
Arif

Output:

distinct: 3
first seen: rina arif zoya
sorted: arif rina zoya

Why it works

Sets ignore repeated adds, so the count and the lists come straight from them, and the choice of set decides the order.

Examples

Example 1 · Input
5
Rina
arif
RINA
zoya
Arif
Expected output
distinct: 3
first seen: rina arif zoya
sorted: arif rina zoya
Example 2 · Input
1
Ada
Expected output
distinct: 1
first seen: ada
sorted: ada

Hints

Hint 1

A LinkedHashSet keeps names in the order first seen; a TreeSet sorts them.

Hint 2

Compare names in lower case, so Ada and ada are the same visitor.

Solution

Show one correct solution (try it yourself first)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine().trim());
        Set<String> firstSeen = new LinkedHashSet<>();
        for (int i = 0; i < n; i++) firstSeen.add(in.nextLine().trim().toLowerCase());
        System.out.println("distinct: " + firstSeen.size());
        System.out.println("first seen: " + String.join(" ", firstSeen));
        System.out.println("sorted: " + String.join(" ", new TreeSet<>(firstSeen)));
    }
}

Lesson: Sets, queues and stacks →