Posts

Showing posts with the label Find the First Repeated Word in a String

Java Program to Find the First Repeated Word in a String

Image
In this section, we will show you two different ways to find first repeated word in a given String in Java. 1.  Using For loop and Map 2. Using  Java 8 Streams Example 1. Using For loop and Map import java.util.LinkedHashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String str = "kotlin java python java go python " + "go java python java go python go" ; Map < String , Integer > map = new LinkedHashMap<>(); String [] words = str .split( " " ); for ( String word : words ) { if ( map .containsKey( word )) { map .put( word , map .get( word ) + 1 ); } else { map .put( word , 1 ); } if ( map .get( word ) > 1 ) { System . out .println( word ); break ; } } } } Here the logic is simple,  split() method is used to split