if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)
However, you can implement an interface with a function like so :
Comparator<String> c = new Comparator<String>() {
int compare(String s, String s2) { ... }
};
and you can use this with inner classes to get an almost-anonymous function :)
Answer from chris on Stack Overflowif you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)
However, you can implement an interface with a function like so :
Comparator<String> c = new Comparator<String>() {
int compare(String s, String s2) { ... }
};
and you can use this with inner classes to get an almost-anonymous function :)
Here's an example of an anonymous inner class.
System.out.println(new Object() {
@Override public String toString() {
return "Hello world!";
}
}); // prints "Hello world!"
This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.
See also
- JLS 15.9.5 Anonymous Class Declarations
Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.
Here's an example of how you can sort a String[] based on String.length().
import java.util.*;
//...
String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
@Override public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"
Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).
See also
- Java Integer: what is faster comparison or subtraction?
- Comparison-by-subtraction is broken in general
- Create a Sorted Hash in Java with a Custom Comparator
- How are Anonymous (inner) classes used in Java?
What makes an anonymous function different from an anonymous class?
Java 8 lambda performance is not great
My assumption is, that Lambdas are a new feature, and JVM optimization are not at the level of native loops yet.
Also you use different method calls in comparison. If you use Double::compare you can not compare it with d < min in performance.
Carry Local Vars Into Anonymous Function?
[Java] ELI5 Lambda expressions
To me, an anonymous function sounds like it is an anonymous class but with a single method to implement. So why give it a fancy name such as an anonymous function when we could have called it an anonymous class with a single function?