Using java only : Write a program to count the number of occurences of each lett
ID: 3604577 • Letter: U
Question
Using java only :
Write a program to count the number of occurences of each letter in a string. The program displays the letters in ascending order.
You should provide two methods. Each method that has an argument of map collection.
the output should be as below :
Sample output:
Enter a string:
Welcome to CECS 277
Map contains:
Sort by keys
Key Value
c 3
e 3
l 1
m 1
o 2
s 1
t 1
w 1
Sort by values
Key Value
c 3
e 3
o 2
l 1
m 1
s 1
t 1
w 1
Explanation / Answer
AlphabetsSortByValueSortByKey.java
import java.util.*;
import java.util.Map.Entry;
public class AlphabetsSortByValueSortByKey {
static Map < Character, Integer > m = new HashMap < Character, Integer > ();
public static void main(String[] args) {
// Declaring variables
String str;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
// Getting the input entered by the user
System.out.print("Enter the String :");
str = sc.nextLine();
char ch;
// Populating each character into the Map
for (int i = 0; i < str.length(); i++) {
ch=str.charAt(i);
if(Character.isAlphabetic(ch))
{
checkMap(Character.toLowerCase(ch));
}
}
Set < Entry < Character, Integer >> set = m.entrySet();
List < Entry < Character, Integer >> list = new ArrayList < Entry < Character, Integer >> (
set);
// Sorting based on values
Collections.sort(list, new Comparator < Map.Entry < Character, Integer >> () {
public int compare(Map.Entry < Character, Integer > o1,
Map.Entry < Character, Integer > o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
System.out.println("Map contains: ");
System.out.println("Sort by values ");
System.out.println("Key Value");
// Displaying the Key value Pairs
for (Map.Entry < Character, Integer > entry: list) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
// Sorting based on keys
Collections.sort(list, new Comparator < Map.Entry < Character, Integer >> () {
public int compare(Map.Entry < Character, Integer > o1,
Map.Entry < Character, Integer > o2) {
return (o1.getKey()).compareTo(o2.getKey());
}
});
System.out.println("Sort by keys ");
System.out.println("Key Value");
// Displaying the Key value Pairs
for (Map.Entry < Character, Integer > entry: list) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
private static void checkMap(char c) {
// Checking whether the word is available in the HashMap
if (m.containsKey(c)) {
m.put(c, m.get(c) + 1);
} else {
// If not available Adding the word to the HashMap
m.put(c, 1);
}
}
}
_________________
Output:
Enter the String :Welcome to CECS 277
Map contains:
Sort by values
Key Value
e 3
c 3
o 2
w 1
t 1
s 1
l 1
m 1
Sort by keys
Key Value
c 3
e 3
l 1
m 1
o 2
s 1
t 1
w 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.