Function Object - in Java

In Java

Java has no first-class functions, so function objects are usually expressed by an interface with a single method (most commonly the Callable interface), typically with the implementation being an anonymous inner class.

For an example from Java's standard library, java.util.Collections.sort takes a List and a functor whose role is to compare objects in the List. Without first-class functions, the function is part of the Comparator interface. This could be used as follows.

List list = Arrays.asList("10", "1", "20", "11", "21", "12"); Comparator numStringComparator = new Comparator { public int compare(String str1, String str2) { return Integer.valueOf(str1).compareTo(Integer.valueOf(str2)); } }; Collections.sort(list, numStringComparator);

Read more about this topic:  Function Object