-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrequencyOfCharacters.java
More file actions
56 lines (46 loc) · 1.45 KB
/
Copy pathFrequencyOfCharacters.java
File metadata and controls
56 lines (46 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.*;
public class Solution {
public static HashMap<Character, Integer> sortByValue(HashMap<Character, Integer> hm)
{
// Create a list from elements of HashMap
List<Entry<Character, Integer>> list =
new LinkedList<Map.Entry<Character, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Character, Integer> >() {
public int compare(Map.Entry<Character, Integer> o1,
Map.Entry<Character, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Character, Integer> temp = new LinkedHashMap<Character, Integer>();
for (Map.Entry<Character, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
public static void main(String args[])
{
String s = "tttree";
HashMap<Character, Integer> hm1 = new HashMap<Character, Integer>();
for(int i =0;i<s.length();i++)
{
Character c = s.charAt(i);
Integer val = hm1.get(c);
if(val!=null)
{
hm1.put(c, val+1);
}
else
{
hm1.put(c, 1);
}
}
System.out.println(hm1);
System.out.println("Sorted hashmap"+ sortByValue(hm1));
}
}