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.
Answer from Mark Bramnik on Stack OverflowVideos
How do you define a function in Java?
What is the difference between a function and a method in Java?
How do you call a function in Java?
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.