Java program for find all duplicate characters in given String
Or
Java program to display only repeated letters in a integer string
Solution 1 :-
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class StreamApi {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter String");
String str = sc.nextLine();
char[] charArray = str.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (char c : charArray) {
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, map.get(c)+1);
}
}
for (Entry<Character, Integer> c : map.entrySet()) {
if (c.getValue() > 1) {
System.out.println(c.getKey());
}
}
}
}
Output :-
Enter String
aabbccd
a
b
c
_________
Enter String
abcdaefg
a
_________
Enter String
programming blog
r
g
m
o
Explanation :-
- Using scanner class we take input from user.
- After we convert string to character array using toCharArray() method.
- For loop through character array and put character as key and count of occurrence that specific character as value.
- After for loop, we loop through map and check all duplicates characters and print them one by one.
Comments
Post a Comment