Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort AtomicLongMap by value

I´m using a guava AtomicLongMap to count the number of phrases in a document.

AtomicLongMap frequentPhrases = AtomicLongMap.create();
frequentPhrases.getAndIncrement(phrase.trim());

Everything works like a charm, but I cannot find a way to sort that Map by the number of occurrences.

like image 516
paul Avatar asked May 28 '26 19:05

paul


1 Answers

You could save the entries to a List, and then sort it by the entry's value, in reverse order:

List<Map.Entry<Object, Long>> sorted = 
    new ArrayList<>(frequentPhrases.asMap().entrySet());
Collections.sort(sorted, Collections.reverseOrder(Map.Entry.comparingByValue()));

for (Map.Entry<Object, Long> entry : sorted) {
    System.out.println(entry); // Or something more useful
}
like image 189
Mureinik Avatar answered May 30 '26 11:05

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!