A Set of Strings

exercise No. 172

Inserting strings into a Set. Create comment in forum

Q:

Create a Set of String instances including duplicates. Iterate over this set and write each value to System.out:

public static void main(String[] args) {

  final Set<String>  names =  new HashSet<String>();
  names.add(...
    ...
  // Iterate over all inserted coordinates
  for (...
}

A:

Inserting some string literals is a trivial task. A for-each loop allows iterating over the set to write its content to standard output:

public static void main(String[] args) {

  final Set<String>  names =  new HashSet<String>();

  names.add("Eve");
  names.add("Jim");
  names.add("Tom");
  names.add("Jim");

  // Iterate over all inserted coordinates
  System.out.println("The set contains " + names.size() + " elements:");
  for (final String s : names) {
    System.out.println(s);
  }
}

Notice the duplicate name "Jim": Since our collection does have set semantics it only contains three elements {"Eve", "Jim", "Tom"}:

The set contains 3 elements:
Tom
Jim
Eve