Find Common Words between two Strings

In this article, we will write a Java program to find Common Words between two Strings.

Solution Steps

  1. Split the input strings with space separator and get the String arrays.
  2. Create ArrayLists from the String Arrays obtained in Step 1.
  3. Use retainAll API to retain only common elements between the ArrayLists.
package com.java.programs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CommonWords {

public static List<String> findCommonWords(String input1,String input2) {
String words1[] = input1.trim().split("\\s+");
String words2[] = input2.trim().split("\\s+");
List<String>list1 = new ArrayList<>(Arrays.asList(words1));
List<String>list2 = Arrays.asList(words2);
list1.retainAll(list2);
return list1;
}

public static void main(String[] args) {
System.out.println(findCommonWords("I am Gyan","I am Rochit"));
}

}
[I, am]

Related Articles: 

Success Strategies: Top 28 Java Programs asked in Interviews

15 Basic Java Programs: Building Foundation

All About String in Java

Leave a Reply

Your email address will not be published. Required fields are marked *