Java Program to Find Duplicate Words in a String - 3 Ways
In this section, we will show you three different ways to find duplicate words in a given String in Java. 1. Using For loop and Map 2. Using Java 8 Streams 3. Using Google Guava MultiSet Example 1: Using For loop and Map import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String string = "Java Python Go C# Java Python Java Go C" ; //Split the string into words based on whitespace String words [] = string .split( " " ); Map < String , Integer > occurrences = new HashMap<>(); //Iterate through String array for ( String word : words ) { Integer oldCount = occurrences .get( word ); if ( oldCount == null ) { oldCount = 0 ; } occurrences .put( word , oldCount + 1 ); } for ( Map . Entry < String , Integer > entry : occurrences .entrySet()) if ( entr...