Recall callbacks.
Arrays.sort
→ This is an already available static method.Comparator
interface provides signature for comparison function.Comparator
and Pass to Arrays.sort
public interface Comparator<T> {
public abstract int compare(T o1, T o2);
}
public class StringCompare implements Comparator<String>{
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
}
String[] strarr = new ... ;
Arrays.sort(starr,StringCompare);
<aside> 💡 Interfaces that define a single function are called Functional Interfaces.
</aside>
Examples: Comparator
, Timerowner
(in callback).
Since these interfaces have only one function in them, and we are creating an object of these interfaces just to use that one function, is there some way to directly pass this function, instead of wrapping them inside an interface?
Functional interface can be visualized as a box carrying just one function. Instead of passing the box onto the next person, can we just pass the function itself, since it is guaranteed to only have one function?
In Python, function names are similar to variable names.
map
is a higher order function. ( Simply a function which takes another function as its argument)def square(x):
return x*x
l = list(map(square,range(100)))
How to do this in Java → Lambda Expressions.
<aside> 💡 Lambda expressions denote anonymous functions.
</aside>
( Parameters ) -> Body