Find the first repeated word in a string | Java program for finding first repeated word in a string ; returns first repeated word ; break string into tokens and then each string into set if a word appeared before appears again , return the word and break ; hashmap for storing word and its count in sentence ; store all the words of string and the count of word in hashmap ; setOfWords . put ( token [ i ] , setOfWords . get ( token [ i ] ) + 1 ) ; word exists ; insert new word to set ; either take a new stream or store the words in vector of strings in previous loop ; driver program
import java . util . * ; class GFG { static String findFirstRepeated ( String s ) { String token [ ] = s . split ( " ▁ " ) ; HashMap < String , Integer > setOfWords = new HashMap < String , Integer > ( ) ; for ( int i = 0 ; i < token . length ; i ++ ) { if ( setOfWords . containsKey ( token [ i ] ) ) else setOfWords . put ( token [ i ] , 1 ) ; } for ( int i = 0 ; i < token . length ; i ++ ) { int count = setOfWords . get ( token [ i ] ) ; if ( count > 1 ) { return token [ i ] ; } } return " NoRepetition " ; } public static void main ( String args [ ] ) { String s = " Ravi ▁ had ▁ been ▁ saying ▁ that ▁ he ▁ had ▁ been ▁ there " ; String firstWord = findFirstRepeated ( s ) ; if ( ! firstWord . equals ( " NoRepetition " ) ) System . out . println ( " First ▁ repeated ▁ word ▁ : : ▁ " + firstWord ) ; else System . out . println ( " No ▁ Repetitionn " ) ; } }