Sort with lambda comparator

Comparator is used to sort the objects by different attributes. If you know which attribute to sort, lambda comparator is the way to go. Lambda comparator is to implement Comparator interface using lambda expression. You can simply put lambda in the place where requires Comparator. Here are the syntax and examples in Java, JavaScript and Python.

In Java, the syntax to compare two object is (a,b) -> –;

In JavaScript, the syntax is (a,b) => –;

In Python, the syntax is key = lambda x: . Lambda is preferred when the comparison is simple .

Sometime you may more have complex comparison involving multiple attributes. For example a People class has first name, last name and age. You want sort by the name first and age second. In Python, you can simply list all the attributes for comparison. For Java and JavaScript, lambda is not that convenient. You need to write custom comparator. Here are the JavaScript comparator and Java Comparator. Use them as template for your projects and save time.




Sort countries by Id:
[(1 Kenya), (2 Mexico), (2 American), (3 Spain), (4 Saudi arabia)]

Sort countries by name:
[(2 American), (1 Kenya), (2 Mexico), (4 Saudi arabia), (3 Spain)]

O Notation:
Time complexity:O(nlogn), n is number of countries
Space complexity: O(n)

Sort with Java comparator – easy code
coding questions series (YouTube)

Comments are closed