Skip to content
Advertisement

Sort a Map<Integer, Map> by value length

I want to sort a Map by value length. For example, I have this code:

JavaScript

and the result is:

JavaScript

so what I want to do is to sort this Map by value length, so it returns:

JavaScript

Advertisement

Answer

You can use Streams to do this:

JavaScript

Basicly you just need a custom Comparator which will get the value of a Map.Entry and compare the size() of that value which in your case is another Map.

Here the full application:

JavaScript

Expected output:

JavaScript

Obviously the exact output depends on the randomized input.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement