Functions In Java?
Benefit of using Java Function rather than normal method? - Stack Overflow
Methods vs Functions in Java
Java: When to use method and when to create a class
Videos
Hi,
I was primarily taught C++ in school so I honestly don't have a good clue as to how Java works. I'm basically wondering how I could use a function in Java. Let's say I write something called int getLargestInt(int n, int arr[]){}, which pulls the largest integer out of an array.
In c++, I would write this in another file, and then I'd include file into the main.cpp to be able to call this function. How would I do something like that in Java?
I've been reading some Cracking the Coding Interview/Programming Interviews Exposed, and they basically just have all of the functions into one huge file, but if I actually try to compile what they have it doesn't run.
Thanks for reading/helping :D
One usage of Function is in Streams. Everyone uses map method these days, I believe:
This map method accepts the Function as a parameter. This allows writing a pretty elegant code - something that could not be achieved before Java 8:
Stream.of("a", "b", "c")
.map(s -> s.toUpperCase())
.collect(Collectors.toList());
// List of A, B, C
Now its true that there are method references and functional interfaces (one of which is Function of course), this lets you using method reference to rewrite the above example as:
Stream.of("a", "b", "c")
.map(String::toUpperCase)
.collect(Collectors.toList())
... but that's only a syntactic sugar - map still accepts the Function as a parameter of course.
Another example that uses Function from Java itself is StackWalker:
Here is an example:
List<StackFrame> frames = StackWalker.getInstance().walk(s ->
s.dropWhile(f -> f.getClassName().startsWith("com.foo."))
.limit(10)
.collect(Collectors.toList()));
}
Note the call to walk method - it accepts a function as a parameter.
So bottom line, it's just yet another tool that can help the programmer to express his/her intentions. Use it wisely wherever appropriate.
Suppose I want to write an applyTwice function:
double applyTwice(double x, Function<Double, Double> f) {
return f.apply(f.apply(x));
}
This needs the function be represented as an object.
Functions are useful when you want to put some structure around arbitrary code supplied by the caller.