Sorting symbol table by value in java
Symbol table give a result sorted by key but how can we sort the symbol table by values. I used Arrays.sort(st,st.get(key))
but gives me an error:
cannot find symbol: method sort(ST,java.lang.开发者_运维知识库Integer)
My program look something like this. Still getting errors:
import java.util.Comparator;
import java.util.Arrays;
public class DictionaryCounter {
private final String key;
public DictionaryCounter (String key){
this.key = key;
}
public static class Frequency implements Comparator<DictionaryCounter>{
public int compare(DictionaryCounter x, DictionaryCounter y){
return x.get(key).compareTo(y.get(key));
}
}
public static void main(String[] args) {
ST<String, Integer> st = new ST<String, Integer>();
//String key;
while (!StdIn.isEmpty()) {
key = StdIn.readString();
if (!st.contains(key))
{ st.put(key, 1); }
else
{ st.put(key,st.get(key) + 1 ); }
}
Arrays.sort(st,new Frequency (key));
for (String s: st.keys()) {
System.out.println(s + " " + st.get(s));
}
}
}
You can't sort quite like that - you need to implement Comparator<T>
- for example:
public class FooComparator implements Comparator<Foo> {
private final String key;
public FooComparator(String key) {
this.key = key;
}
public int compare(Foo x, Foo y) {
return x.get(key).compareTo(y.get(key));
}
}
Then use:
Arrays.sort(st, new FooComparator(key));
(It's hard to guess at the types involved without more information, but hopefully this will give you enough of a start...)
精彩评论