java - How to sort a TreeSet by Value? -
i pretty new treemap
, treeset
, likes , wondering how sort data structures value? realise treeset can sort alphabetical order automatically want order via value? idea on how this?
it prints like...
- aaa: 29
- aaahealthart: 30
- ab: 23
- abbey: 14
- abdomin: 3
- aberdeen: 29
- aberdeenuni: 20
when want print like...
- aaahealthart: 30
- aaa: 29
- aberdeen: 29
- ab: 23
- aberdeenuni: 20
- abbey: 14
- abdomin: 3
here method here...
arraylist<string> fullbagofwords = new arraylist<string>(); public map<string, integer> frequencyone; public void termfrequency() throws filenotfoundexception{ collections.sort(fullbagofwords); set<string> unique = new treeset<string>(fullbagofwords); printwriter pw = new printwriter(new fileoutputstream(frequencyfile)); pw.println("words in tweets : frequency of words"); (string key : unique) { int frequency = collections.frequency(fullbagofwords, key); system.out.println(key + ": " + frequency); pw.println(key + ": " + frequency); } pw.close(); }
thanks guys.
treemap
orders key, don't think can use same implementation sort value. can achieve task different approach:
public map<string, integer> countwords(list<string> words) { map<string, integer> result = new map<>(); (string word : words) { if (result.containskey(word)) { // word in map, increment count int count = result.get(word) + 1; result.put(word, count); } else { result.put(word, 1); } } return result; }
then need sort elements of resulting map. can in following way:
public list<map.entry<string, integer> sortmap(map<string, integer> map) { list<map.entry<string, integer> elements = new linkedlist<>(map.entryset()); collections.sort(elements, new comparator<map.entry<string, integer>>() { public int compare(map.entry<string, integer> o1, map.entry<string, integer> o2 ) { return o1.getvalue().compareto(o2.getvalue()); } }); }
so use first method count word frequency , second sort it.
Comments
Post a Comment