I'm currently working on creating my own custom array in java that uses a binary search tree to store a collection of values.
I want to add a map method that takes Functionas an argument to create a new array. I do not want to evaluate functions unless a specific value is requested. This is pretty easy to do, as lambdas are lazy priced. However, I also want the function to be evaluated only once, even if the result is requested multiple times.
I could create a node that stores the provider and updates the result when evaluating:
class Node<T> {
private T value;
private Supplier<T> supplier;
public T get() {
if (null != value)
return value;
value = supplier.get();
return value;
}
}
... where is supplierobtained from Function, applied to the value in the old version of the stored array.
*. , **.
- Node get:
class Node<T> {
private final Optional<T> value;
private final Supplier<T> supplier;
Node(Supplier<T> supplier, T value) {
this.supplier = supplier;
this.value = Optional.ofNullable(value);
}
public Tuple<Node<T>, T> get() {
if (null != value)
return new Tuple<>(this, value.orElse(null));
T result = supplier.get();
Node<T> newNode = new Node<>(null, result);
return new Tuple<>(newNode, result);
}
}
, ; , . .
- , , , ? .
* , , .
** value a Optional<T>, null , , Optional.empty(), , null. , .
, , , , . . ( 32- ) , .
EDIT:
github. .