A while back, we saw "Frenk"'s approach to making an unreadable pile of lambda-based Java code. Antonio has some more code, which didn't come from Frenk, but possibly from one of Frenk's disciples, who we'll call "Grenk".

Imagine you have a list of users. You want to display those users in order by "lastname, firstname". Your usernames happen to be in the form "firstname.lastname". You also have actual "firstname" and "lastname" fields in your dataset, but ignore those for the moment, because for whatever reason, they never made it to this block of code.

There are a lot of relatively straightforward ways you can solve this problem. Especially, as there is already a TreeMap implementation in Java, which accepts a comparator and ensures the keys are sorted. That wouldn't let Grenk show off the cool new things they learned to do with streams and lambdas. There's a (relatively) new toy in the Java language, and gosh darn it, it needs to be used.

Map<String, ReportPlanDto> mapUsers = getSomeUserDataFromWherever(); Map<String, ReportPlanDto> mapUsersSorted = mapUsers.entrySet().stream().sorted(Map.Entry.comparingByKey((s1, s2) -> { if (s1.split("\\.").length < 2) s1 = s1 + "." + s1; if (s2.split("\\.").length < 2) s2 = s2 + "." + s2; return s1.split("\\.")[1].compareToIgnoreCase(s2.split("\\.")[1]); })).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

An "elegant" solution using "functional" programming techniques. The logic is… interesting. The key comparison is the return s1.split… line, which grabs the bit after the first period, so if the username were joebob.bobsen it compares bobsen with the other string. It's wrong, of course, and it will break in the "unlikely" case that two users have the same last name.

More interesting is the "sanity" check above. Some users, like prince, may not have a last name. Or a first name, I suppose, depending on how you want to look at it. Lots of naming traditions around the world might not guarantee a distinct surname/given-name distinction. So, with that in mind, Grenk solved the problem once and for all… by duplicating the first part of their name as if it were the last name as well.

What we have here is code written in the most complex way it could be, that also happens to be wrong, and frenkly was the absolute worst way to solve the problem.

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!