HashMap in Java

Write a program to print duplicate characters in string with count of them?

import java.util.Map;
import java.util.HashMap;
public class Miscellineous {

public void printDuplicatesCharsandCountOfString() {
System.out.println("Printing the duplicate characters of String");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string that contains duplicate Chars");
String str = sc.nextLine();
HashMap<Character, Integer> hs=new HashMap<Character,Integer >();
char[] ch=str.toCharArray();
for(char h:ch)
if(hs.containsKey(h))
{
hs.put(h, hs.get(h)+1);
}
else
{
hs.put(h, 1);
}
for(Map.Entry m:hs.entrySet()){  
if((int)m.getValue()>1)
{
System.out.println(m.getKey()+" "+m.getValue());  
}
}
}
public static void main(String[] args) {
Miscellineous msc = new Miscellineous();
msc.printDuplicatesCharsandCountOfString();
}
}

Output:
Printing the duplicate characters of String
Enter a string that contains duplicate Chars
hhmmhhmmhhjkkjjll
h 6
j 3
k 2
l 2

m 4

How to get the values from HashMap in java?

 for(String s:hm.values()){  
   System.out.println(s);  

How to get the keys from HashMap in java?

for(int s:hm.keySet()){  
   System.out.println(s);


To get all the entries from a map:
  for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  

No comments:

Post a Comment