Find the duplicate words in a given sentence of strings using the frequency method of the Collections class. This is the third possible solution to solve this problem.
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class DuplicatewordsUsingFrequency {
public static void main(String args[]) {
Scanner inpStr = new Scanner(System.in);
System.out.println("Enter an input sentence");
String sentence = inpStr.nextLine();
//split the given sentence using space delimiter and storing into List collection
List<String> words=Arrays.asList(sentence.split(" "));
Set<String> IndividualWords=new HashSet<String>(words);
//Traversing the words list for from each word in the IndividualWords set to check for more occurrences
for(String eachWord: IndividualWords) {
if (Collections.frequency(words, eachWord) > 1)
System.out.println("The word="+eachWord+" repeated "+Collections.frequency(words, eachWord)+" times");
}
inpStr.close();
}
}
Enter an input sentence
This example shows that This example, This example repeated
The word=This repeated 3 times
The word=example repeated 2 times

Leave a comment