Skip to content

Instantly share code, notes, and snippets.

@ngima
Last active April 24, 2017 06:07
Show Gist options
  • Save ngima/587297c80a6539eecd26f2d2ccde5070 to your computer and use it in GitHub Desktop.
Save ngima/587297c80a6539eecd26f2d2ccde5070 to your computer and use it in GitHub Desktop.
Outputs the character weight like;
package com.yipl.myapplication;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Created by ngima on 4/24/17.
*/
public class CharWeight {
public static void main(String[] args) {
System.out.println(charWeight("hello"));
System.out.println(charWeight("ngima"));
}
static String charWeight(String s) {
s = s.toLowerCase();
Map<Character, Integer> map = new HashMap<>();
StringBuilder stringBuilder = new StringBuilder();
for (char c : s.toCharArray()) {
if (!map.containsKey(c)) {
map.put(c, 1);
continue;
}
map.put(c, (map.get(c) + 1));
}
map = sortByKey(map);
map = sortByValue(map);
for (char key : map.keySet()) {
stringBuilder.append(key + "{" + map.get(key) + "}");
}
return stringBuilder.toString();
}
private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Object>() {
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return ((Comparable<V>) ((Map.Entry<K, V>) (o2)).getValue()).compareTo(((Map.Entry<K, V>) (o1)).getValue());
}
});
Map<K, V> result = new LinkedHashMap<>();
for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext(); ) {
Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
private static <K, V> Map<K, V> sortByKey(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Object>() {
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return ((Comparable<K>) ((Map.Entry<K, V>) (o1)).getKey()).compareTo(((Map.Entry<K, V>) (o2)).getKey());
}
});
Map<K, V> result = new LinkedHashMap<>();
for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext(); ) {
Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment