Open In App

How to Find the Intersection of Two Strings in Java?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We know that the Strings are a collection of characters so if we want to find the intersection of two Strings the simple way is we can compare each character of the first String with the characters of the Second String.

Example to Find the Intersection of Two Strings in Java

There are two strings available s1 and s2 and we want to print the intersection of these two strings in the console.

Input: String s1 = “GeeksforGeeks”
String s2 = “Geeks”

Output: “Geeks”

Approach

  1. So, in the first step we count the frequency of each character present in the string1 here we can use a HashMap which is used to store values in the form of key, and value pair.
  2. Now we create a hashmap. and traverse string1 and add each character along with its frequency which means how many times a character has appeared in the string.
  3. Now we traverse in String2 and check the same character is present in the hashmap.
  4. If the character is present in the hashmap then we decrease the frequency of the character from the hashmap.
  5. And we add those characters who have the positive frequency in the new String.
  6. Then print it on the console.

Below is the implementation of finding the intersection of Two Strings:

Java




// Java Program for Finding
// Intersection of two Strings
import java.io.*;
import java.util.*;
  
// Driver Class
class GFG {
    public static void main(String[] args)
    {
        String s1 = "GeeksforGeeks ";
        String s2 = "Geeks";
        StringBuilder ans = new StringBuilder();
  
        HashMap<Character, Integer> map = new HashMap<>();
        // here we store the frequency of each character
        // present in first string.
        for (int i = 0; i < s1.length(); i++) {
            char character = s1.charAt(i);
            map.put(character,
                    map.getOrDefault(character, 0) + 1);
        }
        // here we check the same character present the
        for (int i = 0; i < s2.length(); i++) {
            char character = s2.charAt(i);
            if (map.containsKey(character)
                && map.get(character) > 0) {
  
                ans.append(character);
                map.put(character, map.get(character) - 1);
            }
        }
        // here we print the output on the console
        System.out.println("The answer is " + ans);
    }
}


Output

The answer is Geeks


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads