Search code examples
javasortinglinkedhashmap

How to get keys of a LinkedHashMap sorted by their entry’s value?


In a graph i associate a node to a quantity : quantities could be redundant and nodes can't, so in order to sort according to ascending quantities i put nodes as keys and quantities as values of a LinkedHashMap and sort it as follows :

 LinkedHashMap<Node, Integer> orderedResult = mapNameToSize.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

But my question is how to get the keys sorted accordingly into a ArrayList?


Solution

  • If all you want is your keys in order of value then you can replace your code with:

    List<Node> sortedNodes = 
        mapNameToSize
        .entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue())
        .map(Map.Entry::getKey)
        .collect(Collectors.toList())
    ;