Home > Blockchain >  Can I use a lambda function like this?
Can I use a lambda function like this?

Time:10-20

I want to try to use lambda functions (which I do not understand well) so I can learn more about them. I have an assignment on trees that has us making a family tree class.

children is a set of all of the children nodes to this node.

/** = the number of nodes in this H1N1Tree.
 * Note: If this is a leaf, the size is 1 (just the root) */
public int size() {
    // TODO 2. This method must be recursive.
    if (children.size() == 0) return 1;
    AtomicInteger sizeOfChildren = new AtomicInteger();
    children.forEach(p -> {sizeOfChildren.addAndGet(p.size());});
    return sizeOfChildren.get();
}

Also as a side question, does this usage of AtomicInteger work similarly to making just an int sizeOfChildren, then running the lambda function with a C pointer to sizeOfChildren?

CodePudding user response:

Yes you can, but it doesn't look very nice. I think I would solve it with a stream instead.

public int size() {
    if (children.size() == 0) return 1;
    return children.stream().mapToInt(c -> c.size()).sum();
}
  • Related