Create a program to discover which words in a list occurs only once and which occurs more than once, but you do not want any duplicates printed out repeatedly. This effect can be achieved by generating two sets: one containing every word in the argument list and the other containing only the duplicates. The words that occur only once are the set difference of these two sets.
Updated: March 7, 2021 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Array - Java Programming
Difficulty: Easy.
Companies who previously asked this: -.
Objective: Create a program to discover which words in a list occurs only once and which occurs more than once, but you do not want any duplicates printed out repeatedly. This effect can be achieved by generating two sets: one containing every word in the argument list and the other containing only the duplicates. The words that occur only once are the set difference of these two sets.
Input: Random list of duplicate and distinct words.
Expected Output: Result will vary based on the user input.
Sikademy Solution
package sikademy;
/**
*
* @author Archangel Macsika
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
// This class creates two list: one containing all words and one containing duplicates
public class DuplicateAndDistinctList {
private static final Logger LOG = Logger.getLogger(DuplicateAndDistinctList.class.getName());
public static void main(String[] args) {
LOG.info("Into Main Class");
String[] setOfWord = { "good", "bad", "good", "people", "time", "time" };
List listOfAllWords = new ArrayList();
List singleWords = new ArrayList();
for (String str : setOfWord) {
listOfAllWords.add(str);
}
for (String word : listOfAllWords) {
if (Collections.frequency(listOfAllWords, word) == 1) {
singleWords.add(word);
}
}
LOG.info("The list of all words are : " + listOfAllWords);
LOG.info("Words with single occurrence are : " + singleWords);
}
}