I don't know how to articulate my question, but it is really simple. I want to create a generic placeholder function that accepts one argument in an already existing function. Let me give you an example. To make things easy, suppose I wanted to know how long it takes for a function to execute in milliseconds.
public class Example{
public static void main(String[] args) {
int arr[] = {30, 8, 21, 19, 50, ... , n};
//needs to accept a function with a parameter as an argument.
timeTakenFunc(foo(arr), arr);
timeTakenFunc(bar(arr), arr);
}
public static void foo(int A[]){
//do stuff
}
public static void bar(int A[]){
//do stuff
}
public static void timeTakenFunc(/*what goes here?*/, int A[]){
long startTime = System.nanoTime();
//placeholder for foo and bar function here
placeholder(A);
long endTime = System.nanoTime();
long duration = ((endTime - startTime) / 1000000);
System.out.println("function took: " + duration + "milliseconds");
}
}
Feel free to edit my question if it needs to be articulated better.
Using Java 8 lambdas and functional interfaces, you can accept a Runnable which performs some generic, unspecified action.
public static void timeTakenFunc(Runnable func) {
long startTime = System.nanoTime();
//placeholder for foo and bar function here
func.run();
long endTime = System.nanoTime();
long duration = ((endTime - startTime) / 1000000);
System.out.println("function took: " + duration + "milliseconds");
}
You would then call it like so:
timeTakenFunc(() -> foo(arr));
timeTakenFunc(() -> bar(arr));
This is shorthand for the pre-lambda equivalent of:
timeTakenFunc(new Runnable() {
@Override public void run() {
foo(arr);
}
});
timeTakenFunc(new Runnable() {
@Override public void run() {
bar(arr);
}
});
I removed the int[] A parameter as it's not necessarily needed here. As you can see, arr can be embedded inside the Runnable. If you wanted to keep it as a parameter then you could switch from Runnable to Consumer<int[]>.
public static void timeTakenFunc(Consumer<int[]> func, int[] A) {
long startTime = System.nanoTime();
//placeholder for foo and bar function here
func.accept(A);
long endTime = System.nanoTime();
long duration = ((endTime - startTime) / 1000000);
System.out.println("function took: " + duration + "milliseconds");
}
timeTakenFunc(arr -> foo(arr), A);
timeTakenFunc(arr -> bar(arr), A);
Or using method references with ::, you can write:
timeTakenFunc(Example::foo, A);
timeTakenFunc(Example::bar, A);
Both of these are equivalent to this pre-lambda code:
timeTakenFunc(new Consumer<int[]>() {
@Override public void accept(int[] arr) {
foo(arr);
}
});
timeTakenFunc(new Consumer<int[]>() {
@Override public void accept(int[] arr) {
bar(arr);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With