java - Sort Map<String, Integer> Largest First Into List<String> Efficiently? -
i have concurrentmap<string, integer>, , i'd list<string> string mapping largest integer first, second largest second, etc.
right have along lines of this:
loop through keyset of map
in loop, loop through "sorted" list<string>
keep looping until key string's respective value less element i of "sorted" list, , insert it.
now work, doubt it's efficient. java 8 have built in sorting algorithms me here?
using streams, write this:
list<string> sorted = map.entryset().stream() .sorted(reverseorder(comparing(entry::getvalue))) .map(entry::getkey) .collect(tolist()); or commented holger:
list<string> sorted = map.entryset().stream() .sorted(comparingbyvalue(reverseorder())) .map(entry::getkey) .collect(tolist()); note static imports:
import static java.util.collections.reverseorder; import static java.util.comparator.comparing; import static java.util.stream.collectors.tolist; i don't know if that's more efficient method can profile both , decide based on actual measurement.
Comments
Post a Comment