Write a program that takes the words in a list and prints out any duplicate words, the number of distinct words, and a list of the words with duplicates eliminated. Hint: Try with HashSet and List implementation.
Updated: March 7, 2021 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: HashSet and List Implementation - Java Programming
Difficulty: Intermediate.
Companies who previously asked this: -.
Objective: Write a program that takes the words in a list and prints out any duplicate words, the number of distinct words, and a list of the words with duplicates eliminated. Hint: Try with HashSet and List implementation.
Input: Random list of duplicate and distinct words.
Expected Output: Duplicate words, result will vary based on the user input.
Sikademy Solution
package sikademy;
/**
*
* @author Archangel Macsika
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
// This class prints the duplicate, distinct and list of words with duplicate eliminated.
public class HashSetAndListImplementation {
private static final Logger LOG = Logger.getLogger(HashSetAndListImplementation.class.getName());
public static void main(String[] args) {
LOG.info("Into main function");
List<String> listOfWords = new ArrayList<String>();
listOfWords.add("one");
listOfWords.add("two");
listOfWords.add("one");
listOfWords.add("two");
listOfWords.add("three");
Iterator iterator;
List<String> distinctList = new ArrayList<String>(new HashSet<String>(listOfWords));
Set<String> duplicateWords = new HashSet<String>();
for (String str : listOfWords) {
if ((Collections.frequency(listOfWords, str)>1)){
duplicateWords.add(str);
}
}
LOG.info("showing duplicate words:");
iterator = duplicateWords.iterator();
while (iterator.hasNext()) {
LOG.info("" + iterator.next());
}
LOG.info("Showing distinct words : ");
iterator = distinctList.iterator();
while (iterator.hasNext()) {
LOG.info("" + iterator.next());
}
}
}