, .
String input = "I have 10 dogs and all the dogs are of different size";
String [] inputSplit = input.split(" ");
Map<String, Integer> map = new HashMap<>();
for (int i=0; i < inputSplit.length; i++) {
String word = inputSplit[i];
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
}
else {
map.put(word, 1);
}
}
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
int compareWordCount = a.getValue().compareTo(b.getValue());
if (compareWordCount == 0) {
return a.getKey().compareTo(b.getKey());
}
return compareWordCount;
}
});
for (int j=0; j < entries.size(); j++) {
System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
}
10 1
I 1
all 1
and 1
are 1
different 1
have 1
of 1
size 1
the 1
dogs 2
String input = "I have 10 dogs and all the dogs are of different size";
String [] inputSplit = input.split(" ");
Map<String, Integer> map = new HashMap<>();
for(int i = 0; i < inputSplit.length; i++){
String word = inputSplit[i];
if(map.containsKey(word)){
map.put(word, map.get(word) + 1);
}
else{
map.put(word, 1);
}
}
List<Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
Comparator <Entry<String, Integer>> ascComparator = new Comparator<Entry<String, Integer>>(){
@Override
public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {
int compareWordCount = a.getValue().compareTo(b.getValue());
if(compareWordCount == 0){
return a.getKey().compareTo(b.getKey());
}
return compareWordCount;
}
};
Comparator <Entry<String, Integer>> descComparator = new Comparator<Entry<String, Integer>>(){
@Override
public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {
int compareWordCount = a.getValue().compareTo(b.getValue());
if(compareWordCount == 0){
return b.getKey().compareTo(a.getKey());
}
return compareWordCount;
}
};
System.out.println("Ascending Sort");
Collections.sort(entries, ascComparator);
for(int j = 0; j < entries.size(); j++){
System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
}
System.out.println("\nDescending Sort");
Collections.sort(entries, descComparator);
for(int j = 0; j < entries.size(); j++){
System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
}
Ascending Sort
10 1
I 1
all 1
and 1
are 1
different 1
have 1
of 1
size 1
the 1
dogs 2
Descending Sort
the 1
size 1
of 1
have 1
different 1
are 1
and 1
all 1
I 1
10 1
dogs 2