I have this generic method to sort a Map by value:
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();
Stream<Map.Entry<K, V>> st = map.entrySet().stream();
st.sorted(Map.Entry.comparingByValue())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
And sometimes I'm getting java.lang.IllegalArgumentException: Comparison method violates its general contract!
. Is there any particular reason this code might behave like this?
I am aware of the duplicate question, but this example involves generics, lambdas and built-in methods, which makes it more complex and I would appreciate some explanation.