Comparator<> vs Compartor.comparing when sorting Java Streams

⚡️Hudson Ⓜ️endes
2 min readNov 13, 2018

Reduce the amount of comparators you have using Comparator.comparing().

When implementing sorting logic, it’s common to choose one out of the 2 routes:
(a) use implementations of Comparator<>
(b) use lambdas

Although these are still good approaches, there is a very handy factory method in the Comparator interface that can generate comparing functions for you in a very sleek way.

Sort using an implementation of Comparator<>

Sort using Lambdas

Sort using Comparator.comparing (my favourite)

Comparators, in general, have the method thenComparing that can be used to concatenate other comparators, so you can combine them together and have a more complex sorting mechanism without having to create a whole new class for it.

Hope it helps!

Wanna keep in Touch? LinkedIn!

My name is Hudson Mendes (@hudsonmendes), I’m a 38 years old coder, husband, father of 3, ex Startup Founder, ex-Peloton L7 Staff Tech Lead/Manager, nearly BSc in Computer Science by the University of London & Senior AI/ML Engineering Manager.

I’ve been on the Software Engineering road for 22+ years, and occasionally write about topics of interest to other Senior Engineering Managers and Staff Machine Learning Engineering with a bit of focus (but not exclusively) on Natural Language Processing.

Join me there, and I will keep you in the loop with my new learnings in AI/ML/LLMs and beyond!

--

--

⚡️Hudson Ⓜ️endes

⚡️Staff AI/ML Engineer & Senior Engineering Manager, #NLP, opinions are my own. https://linkedin.com/in/hudsonmendes