Extract the entries in the list, then sort the list:
List<Map.Entry<String, String>> entries = new ArrayList<Map.Entry<String, String>>(map.entries()); Collections.sort(entries, new Comparator<Map.Entry<String, String>>() { @Override public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) { return Ints.compare(map.get(e2.getKey()).size(), map.get(e1.getKey()).size()); } });
Then iterate over the records.
Edit:
If you want to actually iterate over the internal mapping entries ( Entry<String, Collection<String>> ), follow these steps:
List<Map.Entry<String, Collection<String>>> entries = new ArrayList<Map.Entry<String, Collection<String>>>(map.asMap().entrySet()); Collections.sort(entries, new Comparator<Map.Entry<String, Collection<String>>>() { @Override public int compare(Map.Entry<String, Collection<String>> e1, Map.Entry<String, Collection<String>> e2) { return Ints.compare(e2.getValue().size(), e1.getValue().size()); } });
source share