Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

Java create an ArrayList of Functions with parameters and return values

I want to create a list of functions that I can iterate over and run in sequence.

EDIT: they should be capable of receiving arguments and returning values.

For a dummy example, in Python I can do something like this:

def fn1(s: str) -> int:
    return len(s)

def fn2(s: str) -> int:
    return len(s) + 5

list_of_fns = [
    fn1,
    fn2,
]

results = list(map(lambda fn: fn('hello'), list_of_fns))  # [5, 10]

How can I do the equivalent in Java? Say I have n static methods, how can I create an ArrayList of those methods, then iterate over them and run them in order?

question from:https://stackoverflow.com/questions/65870266/java-create-an-arraylist-of-functions-with-parameters-and-return-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, make sure that the methods you want to put into the list are of the same function type. Roughly speaking, this means that they accept the same number of parameters, and their parameter types and return types are all compatible with each other. If they aren't, then you don't really have a way of calling them afterwards, so that's not very useful.

Then, find a functional interface that represents your function type. Create a List of that interface. There are many built-in ones. For your python examples, they all take a String and return an int, so a ToIntFunction<String> is suitable.

Assuming that staticMethod1, staticMethod2 and staticMethod3 are static methods declared in SomeClass, you can do:

List<ToIntFunction<String>> myMethods = List.of(
    SomeClass::staticMethod1, SomeClass::staticMethod2, SomeClass::staticMethod3
);

To run them you just need to get a ToIntFunction<String> from the list (e.g. by looping), then call the applyAsInt method:

for (ToIntFunction<String> method : myMethods) {
    method.applyAsInt("hello");
}

Note that a different functional interface could have a different name for the method that you need to call to in order to run it.


If you can't find a suitable functional interface for your function type in the JDK, you can make one yourself. It's just an interface with a single method. For example, here is one for methods that take 4 ints and return nothing:

interface IntConsumer4 {
    void accept(int i, int j, int k, int n);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...