In this article, we will write a Java program to find Common Words between two Strings.
Solution Steps
- Split the input strings with space separator and get the String arrays.
- Create ArrayLists from the String Arrays obtained in Step 1.
- 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