Overview
What do you mean by O(1) extra space?
You can create as many variables as you want as long as the number of variables is independent of the size of the array.
Can you discuss the idea that a lambda can manipulate variables within its scope, but outside the scope of whatever uses the variable?
See Scoping.java
Your anonymous functions, like your anonymous inner classes, can refer to local variables and even parameters of the method that creates them, and those variables stick around even after the method exits.
(This breaks in Sam’s stack and heap simplified model.)
Why would you ever do something like that?
It lets you build objects on the fly more easily.
public static Function<Integer,Integer> adder(int addend) {
return (i) -> i + addend;
}
...
map(adder(5), grades);
...
map((i) -> i+5, grades);
Is there a map in Java?
You get to write one.
There are certainly similar things, such as the
forEachin theArrayListclass andmapin theStreamclass.
Can we do more than one thing in a lambda?
Probably. Give it a try. (I will, too, while you’re starting lab.)
Yes. You need braces. And you now need an explicit
return.
I consulted https://www.oreilly.com/library/view/functional-programming-in/9781941222690/f_0088.html in developing that answer.
return (x) -> {
System.err.println("Processing " + x);
if (x < 0) {
return "negative";
} else if (x > 0) {
return "positive";
} else {
return "zero";
}
};
You can see an example in MoreLambdas.java
Oracle provides code for a Person class that you can use.