java 1 input values from a file called wordstxt The file con
java
1) input values from a file called words.txt The file consists of multiple records of multiple words.
2) read all of the words into one ArrayList
3) interrogate the ArrayList and remove all duplicate words.
4) display the ArrayList with all duplicate words removed.
Send me 1) the .java file and 2) a screenprint of the output (which can be the console.).
The is no need for a report on this program.
Solution
ReadWords.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class ReadWords {
public static void main(String[] args) throws FileNotFoundException {
File file = new File(\"words.txt\");
if(file.exists()){
Scanner scan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while(scan.hasNext()){
wordList.add(scan.next());
}
System.out.println(\"ArrayList with all duplicate words: \"+wordList);
Set<String> hs = new HashSet<String>();
hs.addAll(wordList);
wordList.clear();
wordList.addAll(hs);
System.out.println(\"ArrayList with all duplicate words removed: \"+wordList);
}
else{
System.out.println(\"Input file does not exist\");
}
}
}
Output:
ArrayList with all duplicate words: [cat, intolerable, dog, intolerable, elephat, curd, intolerable, daft, cat, elephat, dog]
ArrayList with all duplicate words removed: [daft, cat, intolerable, dog, curd, elephat]
Input File:
cat intolerable dog
intolerable elephat
curd intolerable
daft cat elephat
dog

