r/javahelp • • Jan 14 '20

Recursion with Lambda Expressions

Hello everyone!

I'm having a bit of trouble understanding the lambda expressions. My code snippet should be using a position of a tree and do the traversal with the code. I think I might be looking it at the wrong way. Maybe logic or lack of syntax knowledge of the lambda expressions is what's stopping me of doing what I want.

Any help would be greatly appreciated. Below my code snippet:

@Override
 public void traverseInOrder(Consumer<Position<E>> visit) {
                         visit = p -> {
                        inOrder(p);
          };
           visit.accept(root);
 }

 private  void inOrder(Position<E> p) throws InvalidPositionException {

     BinaryTreeNode<E> t = (BinaryTreeNode<E>) p;
     pt ->  {
                 inOrder(t.left);
                 System.out.println(t.element());
                 inOrder(t.right));
            };
}
16 Upvotes

3 comments sorted by

3

u/ennbou Jan 14 '20

If you want to understand lambda in java, you can take it from geeksforgeeks

3

u/TauPixel Jan 14 '20

Thanks for the pointer I will check it out.

2

u/Roachmeister Java Dev Jan 15 '20

Well, one thing strikes me as wrong right off the bat. As an example, suppose you had the following method:

public void printSomething(String s) {
    s = "hello";
    System.out,println(s);
}

See the problem? I ignore the parameter that is passed in and just print "hello" every time. That's essentially what you're doing in your traverseInOrder method.

Instead, you need to call traverseInOrder with the lambda:

traverseInOrder(p -> inOrder(p));