HashSet
classRead the documentation for Class HashSet<E>
and answer what methods do the following:
HashSet
class.add(value)
adds an element a HashSet.remove(value)
removes an element.contains(value)
checks whether an element is in a HashSet.size()
returns the number of elements in a HashSetWrite an application that reads in a text file with names (one name per line), and prints out each name just once (there are repeated names in the file), in alphabetical order (no need to split the names)
import java.util.ArrayList;
import java.util.Collections;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class UniqueNames {
public static void main(String[] args) throws FileNotFoundException {
File myFile = new File("names.txt");
Scanner myReader = new Scanner(myFile);
HashSet<String> allNames = new HashSet<String>();
while (myReader.hasNext()) {
String line = myReader.nextLine();
allNames.add(line.trim());
}
myReader.close();
ArrayList<String> sortedNames = new ArrayList<String>(allNames);
Collections.sort(sortedNames);
for (String name : sortedNames) System.out.println(name);
}
}