String[] stringArray = {"x", "y", "z", "x", "x", "y", "a"};
final Map<String, Integer> counter = new HashMap<String, Integer>();
for (String str : stringArray)
counter.put(str, 1 + (counter.containsKey(str) ? counter.get(str) : 0));
List<String> list = new ArrayList<String>(counter.keySet());
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String x, String y) {
return counter.get(y) - counter.get(x);
}
});
for (String string : list) {
System.out.println(string)
}
What is the quickest/most efficient way to order this into a smaller Collection in order of how frequent each String is with its frequency?
I tried using a HashMap, which worked, however, I want it to display ["x", "y", "z", "a"]
, and instead displays ["x", "y", "a", "z"]
. I only want the list to sort by frequency not alphabetially as well.
Thanks, i've attached my code to show what i've done.
Replace the compare()
method body with the following:
if (!counter.get(y).equals(counter.get(x)))
return counter.get(y) - counter.get(x);
return x.compareTo(y);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.