Understanding Java 8 Lambda Expressions [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I was reading this article on Java 8 and had the following questions/comments I would appreciate some feedback/response.
1) Is the #FunctionalInterface declaration necessary for the following code? Or could this same code be executed without it and it is for documentation purposes? It is unclear from whether it is necessary from the article.
#FunctionalInterface
private interface DTOSender {
void send(String accountId, DTO dto);
}
void sendDTO(BisnessModel object, DTOSender dtoSender) {
//some logic for sending...
...
dtoSender.send(id, dto);
...
}
2) In general, can a function be passed as an argument to another function in Java 8? My understanding is only data types can be passed as arguments to functions, so I suppose it is not possible as a function is not a data type.
3) Do I need to do anything special to accomplish #2 above or can I just write my definitions of the 2 methods and just pass the one method as a parameter to the other method?
4) Can objects be passed as arguments to another function in Java 8? Do I need to do anything special to accomplish this or can I just write my definitions of the object and method and just pass the object as a parameter to the method?

#Functional Interface is just a hint, so that you don't put more methods into your interface.
It can. Many methods on Stream take functions as parameter: Stream.of(1, 2, 3).forEach(System.out::println).
Lambda is a function instance: Function<Integer, Integer> f = a -> a + 1. Edit: you can pass a function by name using method reference (see 2., println is a regular method).
I don't fully get the question. If the method consumes any argument, that is not primitive, it takes an object (everything in java except for primitives is an object).

The annotation #FunctionalInterface is not mandadory as the doc states.
In order to pass a function to your method, there has to be a matching functional interface.
interface ListFilter<T> {
boolean test(T item);
}
public static <T extends Comparable<T>> List<T> filter(List<T> list, ListFilter<T> filter) {
List<T> filteredList = new ArrayList<>();
for (T t : list) {
if (filter.test(t)) {
filteredList.add(t);
}
}
return filteredList;
}
public static boolean isNumberGreaterThan2(Integer integer){
return integer > 2;
}
public static void main(String[] args) {
List<Integer> list = List.of(1, 2, 3, 4);
filter(list, new ListFilter<Integer>() {
#Override
public boolean test(Integer item) {
return item > 2;
}
});
// or
filter(list, item -> item > 2);
// or
filter(list, Main::isNumberGreaterThan2);
}

Related

Cannot convert from Collection<> to List<> [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to validate a result from a library (Panache / Hibernate using Quarkus) by passing the object to a "validator", where the validator validates that the result is not empty and subsequently returns the passed object back to the caller.
In this example, listAll() is from PanacheEntityBase and simply returns a list of Employee objects. If this List is empty, as in, there are no results in the result set, it does not throw an exception. So to avoid having an empty / null check in every call, I am writing the follow convenience class to validate all results.
In my validator:
public class ResultValidator {
public static <T> Collection<T> validate(Collection<T> result, Class<T> type) throws EmptyResultException {
if (result.isEmpty()) {
throw new EmptyResultException();
}
return result;
}
}
The caller would invoke this like:
return ResultValidator.validate(listAll(), Employee.class);
Rather, I'm having to upcast:
return (List<Employee>) ResultValidator.validate(listAll(), Employee.class);
The code above, that invokes validate, results in a compiler error Cannot convert from Collection<> to List<>. Unless I'm upcasting to List<> or explicitly defining List<> type in my validate implementation, I will get this error.
What do I need to change in my validate(Collection, Class) implementation to avoid upcasting or declaring an explicit type?
If your intent is to return 'self', then:
public static <T, C extends Collection<T>> C validate(C result, Class<T> type) {
// note that requiring a `Class<T>` is a code smell...
if (result.isEmpty()) throw new EmptyResultException();
return result;
}
List<String> list = ...;
list = validate(list, String.class);
now works fine, but note that it is not possible to make a new C instance. You're either returning result straight up, and therefore the fact that validate returns at all is, at best, some code/API convenience but not inherently useful, or, you can't use this, and you'd need a 'make a new collection' factory. That would get you to:
public static <T, C extends Collection<T>> C validate(C result, Class<T> type, Supplier<C> collectionMaker) {
...
}
Where the caller would have to provide something. e.g.:
List<String> list = ...;
validate(list, String.class, () -> new ArrayList<String>());

Pass lambda (Object -> Object) to function in Java [duplicate]

This question already has answers here:
What are functional interfaces used for in Java 8?
(11 answers)
Closed 2 years ago.
what type to use, when i wish to pass a lambda to a function, with lambda accepting and returning an object?
Example of the use can be seen below. I wanna be able to create instances of Foo, where each instance can is able to, in this example, call a prespeficied getter function.
class Foo() {
public ? lambdaFunction;
public Object doSomething(Object arbitraryClass);
return lambdaFunction(arbitraryClass);
}
foo.lambdaFunction = (Object object) -> ((SomeClass) object).getAttribite())
foo.doSomething(someClassInstance);
I have a large number of classes with number of getable attributes, and need to be able to get all of those attributes at different places, but the only thing that changes is the actually classes getter name.
class Foo {
private final Function<Object, ?> func;
public Foo(Function<Object, ?> func) {
this.func = func;
}
public Object doSomething(Object in) {
return func.apply(in);
}
}
But I doubt you actually want that. Java is a nominally typed language - you're supposed to use names, and lots of them. 'Object' doesn't mean much. For example, given that the function needs to be able to convert any object, the function you pass in can't do anything with that object (well, other than toString, hashCode, and the other methods all objects have). The function could cast the input, but that's ugly.
This sounds like a better plan already:
class Foo<F, T> {
private final Function<? super F, ? extends T> func;
public Foo(Function<? super F, ? extends T> func) {
this.func = func;
}
public T doSomething(F in) {
return func.apply(in);
}
}
F and T are short for 'from' and 'to'. The reason it's ? super F is because if you are looking to convert, say, strings to integers, and you have a function that convert any object to an integer, that's good too: You want it to convert either String, or any supertype thereof, and for the 'to', any subtype is also fine.
Extending this answer in light of your recent comments:
Java isn't dynamically typing. No random mysterymeat grabbags of functions that may or may not even make sense given the provided input. Thus, if you want a 'function that describes a setter, e.g. that takes 2 input arguments', then that's a completely different concept: That'd be a function that requires a Receiver and a new Value to set, and returns nothing. 2 inputs, 0 outputs. j.u.f.Function is 1 input, 1 output.
2 inputs, 0 outputs would be java.util.function.BiConsumer<T, U>. Look at the java.util.function API for these types.
class Example {
private String name;
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public static final BiConsumer<Example, String> SETTER = Example::setName;
}
class SomeplaceElse {
void foo() {
Example e = new Example();
String n = "hello";
Example.SETTER.accept(e, n);
System.out.println(e.getName()); // prints 'hello'
}
}
java.util.function.Function<T,R>, where T is the type of its argument and R is its return type.
But if you really plan having a public Function<Object,Object> lambdaFunction; field, that may not be the best design ever, you should use your actual types, not casting things back and forth.
For the extension appearing in a comment: look into the containing package, https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/function/package-summary.html to see what else is "ready".
For having 2 arguments and returning something, you can use BiFunction<T,​U,​R>. For having 2 arguments and returning nothing, you can use BiConsumer<T,​U>. And if you don't find what you need, then you can create your own interface and tag it as #FunctionalInterface. But that leads to a duplicate question, What are functional interfaces used for in Java 8?
java.util.function.Function is the type to use.

By using Generics How can I pass Map as a Collection to my method? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My code as Follows:
public class CalledClass
{
public static <T> List<T> conditionMethod(**<T> map,Class<T> tableName)
{
//B.L
return li;
}
}
public class PureCoding
{
public static <T> void main(String[] args)
{
Map<T,T> map = new HashMap<T,T>();
CalledClass.conditionMethod(map,HomeWorkPojo.class);
}
}
By this way I can't call method in CalledClass. How can I call the method. Here I want to pass Collection type Map and Class Name as Parameters to my conditionMethod().
In place of ** What type I will give.?
So...if I understand you correctly, you wish to pass a Map and Class to your method. In that case, the only generics you'd need are the bounds to the key and value of the map, and the type of Class you want (or wildcard):
public static <K, V> List<V> conditionMethod(Map<K, V> map, Class<?> tableName) {
// implementation to go here
}
Remember what generics actually provide - compile time safety with regards to types. They're not some magic bullet; you use them as they are intended to be used.

Java Blocks, Closures, Lambdas... simply explained [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
For those who ever wrote in C, C++ or ObjectiveC, understand Blocks is very simple. Why it's so difficult to get the concept in Java (8)?
I will answer my question!
Block
Just a list of statements surrounded by curly braces. That's all. A block is executed by executing its individual statements in sequence. It's nothing like the thing called a "block" in, for example, the Ruby programming language.
Closure
Java does not have closures, but it has something that looks like one:
int limit = ...;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for (int i=0 ; i<limit ; i++) { ... }
}
});
That may look like the run() method refers to the variable limit in the outer scope, but it won't compile unless the variable limit is effectively immutable. What's really happening here is that the anonymous inner class has a member variable named limit, and a hidden constructor that takes an argument named limit, and the value is supplied to the constructor by copying the value of limit from the surrounding scope.
Lambda
More smoke and mirrors. The value of a lambda expression in Java is not a function: It's an instance of an anonymous inner class that implements a functional interface. The same code that I wrote above could be written more concisely as a Java lambda expression:
int limit = ...;
Thread t = new Thread(() -> {
for (int i=0 ; i<limit ; i++) { ... }
});
Java8 introduces the idea of an #Functional interface type which must declare exactly one method. In this case, they've retconned the java.lang.Runnable class to be #Functional
When the compiler reads the code above, it knows to make the anonymous class implement the Runnable interface because that's the only type that is accepted by the Thread constructor, and it knows that the body of the lambda should become the run() method, because that's the only method declared by Runnable.
All you need to understand is “type”.
A variable has a type. Eg:
int i, double d…
An object has a type (a class). Eg:
String s, Number n, Object o, MyClass m…
A function has a type. Eg:
void function () <= this type is: a function with no return and no param.
void function (type param) <= this type is: a function with no return with a param of type ‘type’
type function (type param) <= this type is: a function with a return of type ‘type’ and a param of type ‘type’
What is a block/closure/lambda?
It is basically a local function of a given type passed to an other function as parameter.
So we heard: a function that takes a function of a given type as parameter.
And the function which receive the function and launches it!
The main usage is: CallBack and Comparaison functions. But the dream up is open.
We can draw that as:
type function(type function_param) {
excute the function_param
}
How to say this in Java.
1/ declare the type of the block/closure/lambda
2/ create the function (in a class or not) which get that kind of type as param
3/ create the local function of the type of the block/closure/lambda
4/ pass it as param to the function which use it.
Eg:
// 1 declaring the type of block/closure/lambda
interface CallBack {
public int function(String string);
}
class MyClass {
private String name;
MyClass(String name) { this.name = name; }
void display () { System.out.println(this.name); }
// 2 creating the function that which that kind of type as param
int myFunction(CallBack funcCallBack) {
return funcCallBack.function(name);
}
}
public class Main {
public static void main(String[] args) {
// 3 Create the local function of the type of the block/closure/lambda
CallBack message = (String string) -> {
System.out.println("Message: "+string);
return 1;
};
MyClass mc = new MyClass("MyClass");
mc.display();
// 4 pass it as param to the function which use it.
int res = mc.myFunction(message);
System.out.println(res);
}
}
output
MyClass
Message: MyClass
1

What's the nearest substitute for a function pointer in Java?

I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?
Anonymous inner class
Say you want to have a function passed in with a String param that returns an int.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
interface StringFunction {
int func(String param);
}
A method that takes the pointer would just accept StringFunction instance like so:
public void takingMethod(StringFunction sf) {
int i = sf.func("my string");
// do whatever ...
}
And would be called like so:
ref.takingMethod(new StringFunction() {
public int func(String param) {
// body
}
});
EDIT: In Java 8, you could call it with a lambda expression:
ref.takingMethod(param -> bodyExpression);
For each "function pointer", I'd create a small functor class that implements your calculation.
Define an interface that all the classes will implement, and pass instances of those objects into your larger function. This is a combination of the "command pattern", and "strategy pattern".
#sblundy's example is good.
When there is a predefined number of different calculations you can do in that one line, using an enum is a quick, yet clear way to implement a strategy pattern.
public enum Operation {
PLUS {
public double calc(double a, double b) {
return a + b;
}
},
TIMES {
public double calc(double a, double b) {
return a * b;
}
}
...
public abstract double calc(double a, double b);
}
Obviously, the strategy method declaration, as well as exactly one instance of each implementation are all defined in a single class/file.
You need to create an interface that provides the function(s) that you want to pass around. eg:
/**
* A simple interface to wrap up a function of one argument.
*
* #author rcreswick
*
*/
public interface Function1<S, T> {
/**
* Evaluates this function on it's arguments.
*
* #param a The first argument.
* #return The result.
*/
public S eval(T a);
}
Then, when you need to pass a function, you can implement that interface:
List<Integer> result = CollectionUtilities.map(list,
new Function1<Integer, Integer>() {
#Override
public Integer eval(Integer a) {
return a * a;
}
});
Finally, the map function uses the passed in Function1 as follows:
public static <K,R,S,T> Map<K, R> zipWith(Function2<R,S,T> fn,
Map<K, S> m1, Map<K, T> m2, Map<K, R> results){
Set<K> keySet = new HashSet<K>();
keySet.addAll(m1.keySet());
keySet.addAll(m2.keySet());
results.clear();
for (K key : keySet) {
results.put(key, fn.eval(m1.get(key), m2.get(key)));
}
return results;
}
You can often use Runnable instead of your own interface if you don't need to pass in parameters, or you can use various other techniques to make the param count less "fixed" but it's usually a trade-off with type safety. (Or you can override the constructor for your function object to pass in the params that way.. there are lots of approaches, and some work better in certain circumstances.)
Method references using the :: operator
You can use method references in method arguments where the method accepts a functional interface. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.)
IntBinaryOperator is a functional interface. Its abstract method, applyAsInt, accepts two ints as its parameters and returns an int. Math.max also accepts two ints and returns an int. In this example, A.method(Math::max); makes parameter.applyAsInt send its two input values to Math.max and return the result of that Math.max.
import java.util.function.IntBinaryOperator;
class A {
static void method(IntBinaryOperator parameter) {
int i = parameter.applyAsInt(7315, 89163);
System.out.println(i);
}
}
import java.lang.Math;
class B {
public static void main(String[] args) {
A.method(Math::max);
}
}
In general, you can use:
method1(Class1::method2);
instead of:
method1((arg1, arg2) -> Class1.method2(arg1, arg2));
which is short for:
method1(new Interface1() {
int method1(int arg1, int arg2) {
return Class1.method2(arg1, agr2);
}
});
For more information, see :: (double colon) operator in Java 8 and Java Language Specification §15.13.
You can also do this (which in some RARE occasions makes sense). The issue (and it is a big issue) is that you lose all the typesafety of using a class/interface and you have to deal with the case where the method does not exist.
It does have the "benefit" that you can ignore access restrictions and call private methods (not shown in the example, but you can call methods that the compiler would normally not let you call).
Again, it is a rare case that this makes sense, but on those occasions it is a nice tool to have.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Main
{
public static void main(final String[] argv)
throws NoSuchMethodException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
final String methodName;
final Method method;
final Main main;
main = new Main();
if(argv.length == 0)
{
methodName = "foo";
}
else
{
methodName = "bar";
}
method = Main.class.getDeclaredMethod(methodName, int.class);
main.car(method, 42);
}
private void foo(final int x)
{
System.out.println("foo: " + x);
}
private void bar(final int x)
{
System.out.println("bar: " + x);
}
private void car(final Method method,
final int val)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
method.invoke(this, val);
}
}
If you have just one line which is different you could add a parameter such as a flag and a if(flag) statement which calls one line or the other.
You may also be interested to hear about work going on for Java 7 involving closures:
What’s the current state of closures in Java?
http://gafter.blogspot.com/2006/08/closures-for-java.html
http://tech.puredanger.com/java7/#closures
New Java 8 Functional Interfaces and Method References using the :: operator.
Java 8 is able to maintain method references ( MyClass::new ) with "# Functional Interface" pointers. There are no need for same method name, only same method signature required.
Example:
#FunctionalInterface
interface CallbackHandler{
public void onClick();
}
public class MyClass{
public void doClick1(){System.out.println("doClick1");;}
public void doClick2(){System.out.println("doClick2");}
public CallbackHandler mClickListener = this::doClick;
public static void main(String[] args) {
MyClass myObjectInstance = new MyClass();
CallbackHandler pointer = myObjectInstance::doClick1;
Runnable pointer2 = myObjectInstance::doClick2;
pointer.onClick();
pointer2.run();
}
}
So, what we have here?
Functional Interface - this is interface, annotated or not with #FunctionalInterface, which contains only one method declaration.
Method References - this is just special syntax, looks like this, objectInstance::methodName, nothing more nothing less.
Usage example - just an assignment operator and then interface method call.
YOU SHOULD USE FUNCTIONAL INTERFACES FOR LISTENERS ONLY AND ONLY FOR THAT!
Because all other such function pointers are really bad for code readability and for ability to understand. However, direct method references sometimes come handy, with foreach for example.
There are several predefined Functional Interfaces:
Runnable -> void run( );
Supplier<T> -> T get( );
Consumer<T> -> void accept(T);
Predicate<T> -> boolean test(T);
UnaryOperator<T> -> T apply(T);
BinaryOperator<T,U,R> -> R apply(T, U);
Function<T,R> -> R apply(T);
BiFunction<T,U,R> -> R apply(T, U);
//... and some more of it ...
Callable<V> -> V call() throws Exception;
Readable -> int read(CharBuffer) throws IOException;
AutoCloseable -> void close() throws Exception;
Iterable<T> -> Iterator<T> iterator();
Comparable<T> -> int compareTo(T);
Comparator<T> -> int compare(T,T);
For earlier Java versions you should try Guava Libraries, which has similar functionality, and syntax, as Adrian Petrescu has mentioned above.
For additional research look at Java 8 Cheatsheet
and thanks to The Guy with The Hat for the Java Language Specification §15.13 link.
#sblundy's answer is great, but anonymous inner classes have two small flaws, the primary being that they tend not to be reusable and the secondary is a bulky syntax.
The nice thing is that his pattern expands into full classes without any change in the main class (the one performing the calculations).
When you instantiate a new class you can pass parameters into that class which can act as constants in your equation--so if one of your inner classes look like this:
f(x,y)=x*y
but sometimes you need one that is:
f(x,y)=x*y*2
and maybe a third that is:
f(x,y)=x*y/2
rather than making two anonymous inner classes or adding a "passthrough" parameter, you can make a single ACTUAL class that you instantiate as:
InnerFunc f=new InnerFunc(1.0);// for the first
calculateUsing(f);
f=new InnerFunc(2.0);// for the second
calculateUsing(f);
f=new InnerFunc(0.5);// for the third
calculateUsing(f);
It would simply store the constant in the class and use it in the method specified in the interface.
In fact, if KNOW that your function won't be stored/reused, you could do this:
InnerFunc f=new InnerFunc(1.0);// for the first
calculateUsing(f);
f.setConstant(2.0);
calculateUsing(f);
f.setConstant(0.5);
calculateUsing(f);
But immutable classes are safer--I can't come up with a justification to make a class like this mutable.
I really only post this because I cringe whenever I hear anonymous inner class--I've seen a lot of redundant code that was "Required" because the first thing the programmer did was go anonymous when he should have used an actual class and never rethought his decision.
The Google Guava libraries, which are becoming very popular, have a generic Function and Predicate object that they have worked into many parts of their API.
One of the things I really miss when programming in Java is function callbacks. One situation where the need for these kept presenting itself was in recursively processing hierarchies where you want to perform some specific action for each item. Like walking a directory tree, or processing a data structure. The minimalist inside me hates having to define an interface and then an implementation for each specific case.
One day I found myself wondering why not? We have method pointers - the Method object. With optimizing JIT compilers, reflective invocation really doesn't carry a huge performance penalty anymore. And besides next to, say, copying a file from one location to another, the cost of the reflected method invocation pales into insignificance.
As I thought more about it, I realized that a callback in the OOP paradigm requires binding an object and a method together - enter the Callback object.
Check out my reflection based solution for Callbacks in Java. Free for any use.
Sounds like a strategy pattern to me. Check out fluffycat.com Java patterns.
oK, this thread is already old enough, so very probably my answer is not helpful for the question. But since this thread helped me to find my solution, I'll put it out here anyway.
I needed to use a variable static method with known input and known output (both double). So then, knowing the method package and name, I could work as follows:
java.lang.reflect.Method Function = Class.forName(String classPath).getMethod(String method, Class[] params);
for a function that accepts one double as a parameter.
So, in my concrete situation I initialized it with
java.lang.reflect.Method Function = Class.forName("be.qan.NN.ActivationFunctions").getMethod("sigmoid", double.class);
and invoked it later in a more complex situation with
return (java.lang.Double)this.Function.invoke(null, args);
java.lang.Object[] args = new java.lang.Object[] {activity};
someOtherFunction() + 234 + (java.lang.Double)Function.invoke(null, args);
where activity is an arbitrary double value. I am thinking of maybe doing this a bit more abstract and generalizing it, as SoftwareMonkey has done, but currently I am happy enough with the way it is. Three lines of code, no classes and interfaces necessary, that's not too bad.
To do the same thing without interfaces for an array of functions:
class NameFuncPair
{
public String name; // name each func
void f(String x) {} // stub gets overridden
public NameFuncPair(String myName) { this.name = myName; }
}
public class ArrayOfFunctions
{
public static void main(String[] args)
{
final A a = new A();
final B b = new B();
NameFuncPair[] fArray = new NameFuncPair[]
{
new NameFuncPair("A") { #Override void f(String x) { a.g(x); } },
new NameFuncPair("B") { #Override void f(String x) { b.h(x); } },
};
// Go through the whole func list and run the func named "B"
for (NameFuncPair fInstance : fArray)
{
if (fInstance.name.equals("B"))
{
fInstance.f(fInstance.name + "(some args)");
}
}
}
}
class A { void g(String args) { System.out.println(args); } }
class B { void h(String args) { System.out.println(args); } }
Check out lambdaj
http://code.google.com/p/lambdaj/
and in particular its new closure feature
http://code.google.com/p/lambdaj/wiki/Closures
and you will find a very readable way to define closure or function pointer without creating meaningless interface or use ugly inner classes
Wow, why not just create a Delegate class which is not all that hard given that I already did for java and use it to pass in parameter where T is return type. I am sorry but as a C++/C# programmer in general just learning java, I need function pointers because they are very handy. If you are familiar with any class which deals with Method Information you can do it. In java libraries that would be java.lang.reflect.method.
If you always use an interface, you always have to implement it. In eventhandling there really isn't a better way around registering/unregistering from the list of handlers but for delegates where you need to pass in functions and not the value type, making a delegate class to handle it for outclasses an interface.
None of the Java 8 answers have given a full, cohesive example, so here it comes.
Declare the method that accepts the "function pointer" as follows:
void doCalculation(Function<Integer, String> calculation, int parameter) {
final String result = calculation.apply(parameter);
}
Call it by providing the function with a lambda expression:
doCalculation((i) -> i.toString(), 2);
If anyone is struggling to pass a function that takes one set of parameters to define its behavior but another set of parameters on which to execute, like Scheme's:
(define (function scalar1 scalar2)
(lambda (x) (* x scalar1 scalar2)))
see Pass Function with Parameter-Defined Behavior in Java
Since Java8, you can use lambdas, which also have libraries in the official SE 8 API.
Usage:
You need to use a interface with only one abstract method.
Make an instance of it (you may want to use the one java SE 8 already provided) like this:
Function<InputType, OutputType> functionname = (inputvariablename) {
...
return outputinstance;
}
For more information checkout the documentation: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Prior to Java 8, nearest substitute for function-pointer-like functionality was an anonymous class. For example:
Collections.sort(list, new Comparator<CustomClass>(){
public int compare(CustomClass a, CustomClass b)
{
// Logic to compare objects of class CustomClass which returns int as per contract.
}
});
But now in Java 8 we have a very neat alternative known as lambda expression, which can be used as:
list.sort((a, b) -> { a.isBiggerThan(b) } );
where isBiggerThan is a method in CustomClass. We can also use method references here:
list.sort(MyClass::isBiggerThan);
The open source safety-mirror project generalizes some of the above mentioned solutions into a library that adds functions, delegates and events to Java.
See the README, or this stackoverflow answer, for a cheat sheet of features.
As for functions, the library introduces a Fun interface, and some sub-interfaces that (together with generics) make up a fluent API for using methods as types.
Fun.With0Params<String> myFunctionField = " hello world "::trim;`
Fun.With2Params<Boolean, Object, Object> equals = Objects::equals;`
public void foo(Fun.With1ParamAndVoid<String> printer) throws Exception {
printer.invoke("hello world);
}
public void test(){
foo(System.out::println);
}
Notice:
that you must choose the sub-interface that matches the number of parameters in the signature you are targeting. Fx, if it has one parameter, choose Fun.With1Param.
that Generics are used to define A) the return type and B) the parameters of the signature.
Also, notice that the signature of the Method Reference passed to the call to the foo() method must match the the Fun defined by method Foo. If it do not, the compiler will emit an error.

Categories

Resources