-2

I know that some language such as python can do this:

maps = []
cur = 1
maps.append(function)
for func in self.maps:
    cur = func(cur)

It adds a function to list and can iteratively call it. I'm wondering if Java can do the similar thing, if yes, how can it be done?

xiaodelaoshi
  • 623
  • 1
  • 7
  • 22
  • 1
    Hint: use a `List`. – Rob Spoor Aug 23 '22 at 15:29
  • The proper way to do that in Java is to go through functional interfaces and then use for example method references `List tasks = List.of(Foo::printHello);` (or lambdas or anonymous classes or regular classes that implement the interface) – Zabuzard Aug 23 '22 at 15:29
  • I'm not sure why this question asking about Lists is closed as duplicates asking about Arrays. They are different entities, are they not? It seems to be the case since the answers on the targets say "no" but the answer here says "yes". – TylerH Aug 26 '22 at 15:18
  • @TylerH I agree. I reopened it. – WJS Aug 28 '22 at 11:23

1 Answers1

3

Yes. You can store a lambda in a list.

List<Function<Double, Double>> list = new ArrayList<>();
list.add(v->v*20);
list.add(v->v*30);

System.out.println(list.get(0).apply(10.));
System.out.println(list.get(1).apply(10.));

prints

200
300
WJS
  • 36,363
  • 4
  • 24
  • 39
  • 3
    This example might be better off using `DoubleUnaryOperator` (to avoid boxing/unboxing) – Mark Rotteveel Aug 23 '22 at 15:31
  • True. Didn't think of it. But since there are so many options, in terms of number of arguments, types, etc, I guess this will still drive home the point. – WJS Aug 23 '22 at 15:33