Quote:
try sorting a HashMap by its values
Rule 1 of Java Club.
Code:
HashMap<String, Integer> a = someHashMap;
a.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, HashMap::new));
Java is the ****ing worst. I come from C#, which is like Java that is actually intuitive, is richly-featured and works, so coming to Java is like getting downgraded from power tools to a hammer and chisel. Java streams are a hell of a lot better than having no functional programming at all, but LINQ in C# is about a zillion times better. The main problem with Java streams is that they are unintuitive and the errors are all utterly incomprehensible. For instance, if I try to assign the result of the above to a HashMap<String, Integer>, everything is fine. But if I try to assign it to, say, a List<String>, this is the result:
Quote:
Error: (73, 126) java: incompatible types: inference variable R has incompatible bounds
upper bounds: java.util.List<java.lang.String>,java.util.Map<K,U >,java.lang.Object
lower bounds: java.util.HashMap<K,V>
OK, something about incompatible types, no big deal, we'll just mouse over the toMap and see what type it produces...
Oh.
In C# it will just go "yo, this produces a Map<String, Integer> and that's not what your variable is". I don't get why it's hard, but Java streams always error out with total nonsense and I have to go google for what I'm doing wrong.
My favourite piece of Java hate, which I've posted before ITT, is that there's an Arrays.toList() method, which takes an array and produces an ArrayList. Easy! Except that this ArrayList is not a java.util.ArrayList, but a java.arrays.ArrayList, which looks and acts exactly the same unless you try to mutate it, in which case it will compile and then throw an exception at runtime. I consider this proof that the programmers of Java actually were trolling us.