java - How to count and sort repeating strings -


i have got string of names

string str = "a. walker, l. gordon, c. riley, l. gordon"; 

i need count name occurancies , sort occurancies biggest lowest.

i have done countung part, need sort it.

string[] array = str.split(", ");          list aslist = arrays.aslist(array); set<string> myset = new hashset<string>(aslist); for(string s: myset)     system.out.println(s + " " +collections.frequency(aslist,s)); 

output should this

l. gordon 2, a. walker 1, c. riley 1 

you can this:

public class test {     static class namefreq {         public namefreq(string name, int freq) {             this.name = name;             this.freq = freq;         }         string name;         int freq;         @override         public string tostring() {             return name + " " + freq;         }     }     public static void main(string[] args) throws exception {         string str = "a. walker, l. gordon, c. riley, l. gordon";         map<string, namefreq> map = new hashmap<>();         string[] array = str.split("\\s*,\\s*");         for(string name : array) {             namefreq namefreq = map.get(name);             if( namefreq==null )                 map.put(name, new namefreq(name, 1));             else                 namefreq.freq++;         }          list<namefreq> list = new arraylist<>(map.values());         collections.sort(list, new comparator<namefreq>() {             @override             public int compare(namefreq o1, namefreq o2) {                 return integer.compare(o2.freq, o1.freq);             }         });          system.out.println(list);         //output: [l. gordon 2, a. walker 1, c. riley 1]     } } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -