DEV Community

Suresh Ayyanna
Suresh Ayyanna

Posted on

Find Duplicate String and Letters from a Given string - Java(Collections)

**

Program to find Duplicate String and Letters from a Given string - Java(Collections)

**

package Test;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Program1 {

    public static void findDuplicateWords(String str) {
        // 1. Split the String - String Array formation
        String[] s = str.split(" ");

        // 2. Crate a HashMap to get key-value pair
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (String temp : s) {
            if (map.get(temp) != null) {
                map.put(temp, map.get(temp) + 1);
            } else
                map.put(temp, 1);
        }

        // 3. To find duplicate words from keyValue set
        Set<Map.Entry<String, Integer>> data = map.entrySet();
        for (Map.Entry<String, Integer> dup : data) {
            if (dup.getValue() > 1)
                System.out.println("The word : '" + dup.getKey() + "' appeared - " + dup.getValue() + " times");

        }
    }

    public static void findDuplicateLetters(String str) {
        //1.Remove whitespaces
        str = str.replace(" ", "");

        //2.Convert to Lower case all letters
        str=str.toLowerCase();

        //3. create Hash map to get key-value pair
        HashMap<Character, Integer> hmap = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (hmap.get(ch) != null) {
                hmap.put(ch, hmap.get(ch) + 1);
            } else
                hmap.put(ch, 1);
        }
        Set<Map.Entry<Character, Integer>> data = hmap.entrySet();
        for (Map.Entry<Character, Integer> dup : data) {
            if (dup.getValue() > 1)
                System.out.println("The word : '" + dup.getKey() + "' appeared - " + dup.getValue() + " times");
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the Stirng");

        String str = input.nextLine();

        findDuplicateWords(str);
        findDuplicateLetters(str);

    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)