Java – How do I sort map entries by value size when map values are collections?

How do I sort map entries by value size when map values are collections?… here is a solution to the problem.

How do I sort map entries by value size when map values are collections?

Is there a way to sort map entries by value for the value of the collection? I want to sort entries by the size of the collection. My code so far:

public Map<Object, Collection<Object>> sortByCollectionSize() {
    return myMap.entrySet().stream().sorted(Map.Entry.<Object, Collection<Object>>comparingByValue())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

Related Problems and Solutions