Skip to content

Instantly share code, notes, and snippets.

@ufuk
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save ufuk/79fd2766a4a49a7b8072 to your computer and use it in GitHub Desktop.

Select an option

Save ufuk/79fd2766a4a49a7b8072 to your computer and use it in GitHub Desktop.
Sort Map By Collection Value Size (descending)

Note: Add a new criteria to compare method if sizes are equal.

Map<X, Set<Y>> notSortedMap = ...

Map<X, Set<Y>> sortedMap = new TreeMap<>(new Comparator<X>() {
    @Override
    public int compare(X firstX, X secondX) {
        return Integer.valueOf(notSortedMap.get(secondX).size()).compareTo(Integer.valueOf(notSortedMap.get(firstX).size()));
    }
});

sortedMap.putAll(notSortedMap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment