HashMap keys to sorted List The idea is to obtain the keys as a list ordered by the natural ordering of the keys but first of them all the ones that have priority, stated by the method hasPriority(). The custom comparator code block feels out of place and I wonder if it is possible to improve the code:

private List&lt;String&gt; orderedKeys() {
    return this.variables.entrySet()
            .stream()
            .sorted((e1, e2) -&gt; {
                if (e1.getValue().hasPriority() &amp;&amp; e2.getValue().hasPriority()) return e1.getKey().compareTo(e2.getKey());
                if (e1.getValue().hasPriority()) return -1;
                if (e2.getValue().hasPriority()) return 1;
                return e1.getKey().compareTo(e2.getKey());
            })
            .map(e -&gt; e.getKey())
            .collect(Collectors.toList());
}


Edit: this.variables is a reference to a Map of String Keys and custom objects as values that have the boolean method hasPriority().
You can use the new utilities in the comparator class. Unfortunately you'll have to help the compiler a bit with the generic type induction.

Assuming, that the value class is "Whatever", this can be done like this:

    map.entrySet().stream()
        .sorted(Comparator.comparing((Map.Entry&lt;String, Whatever&gt; e) -&gt; e.getValue().hasPriority())
                          .thenComparing(Map.Entry::getKey))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());