Sort with lambda comparator

Comparator is used to sort the objects by different attributes. You can simply put lambda in the place where requires Comparator. Lambda is preferred when the comparison is simple. Here are the syntax and examples in Java, JavaScript and Python.

How to use lambda comparator in Java?

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

How to use lambda comparator in JavaScript?

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

How to use lambda comparator in Python?

In Python, the syntax is key = lambda x:

Sometime you may have complex comparisons 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 list all the attributes for comparison. For Java and JavaScript, lambda is not that convenient. You need to write custom comparator.




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)

HashMap sort by value
HashMap sort by key

Comments are closed