Sorting AtomicLongMap by value
I am using 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 can't find a way to sort this card by the number of occurrences.
+3
source to share
1 answer
You can save records to List
, and then sort them by record 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
}
+1
source to share