Whffgfv Obggcg
Whffgfv Obggcg

Reputation: 31

Passing the method to method

I have a method which uses Deque. In 1 place, sometimes I want to Deque.pullFirst() and sometimes Deque.pullLast(). It should depend on one of the arguments passed to the method. How do this with Java 8?

This is my try with Callable I know that it doesn't work but now you can understand what I want to achieve:

public class AppMain {
    public void iterateThroughQueue(Callable callable) { // error
         Deque<Integer> deq = new ArrayDeque<>();

         deq.add(1);
         deq.add(2);
         deq.add(3);

         for (int i = 0; i < 3; i++) {
                System.out.println(callable.apply(deq)); // error!
         }
         System.out.println("size after iteration = "  + deq.size());
   }

   public static void main(String[] args) {  
         AppMain.iterateThroughQueue(Deque::pollFirst); // error!
   }
}

Upvotes: 0

Views: 224

Answers (2)

Nyamiou The Galeanthrope
Nyamiou The Galeanthrope

Reputation: 1224

Method references are either:

  • Consumer<T>, which means they take a parameter and return nothing. For example System.out::println is a Consumer<String>.
  • Producer<T>, which means they take no parameter and return something. For example UUID::randomUUID is a Producer<UUID>.
  • Function<T,Z>, which means they take a parameter of type T (can be the instance on which to apply the method) and return a result of type Z, in your case Deque::pollFirst take is a Function<Deque<Integer>, Integer>. Another example is deq::add where deq is an instance of Deque<Integer> which would be a Function<Integer, Boolean> .

So you should be using Function<Deque<Integer>, Integer> instead of Callable which is for something completely different. Also iterateThroughQueue(...) need to be static.

Upvotes: 3

gil.fernandes
gil.fernandes

Reputation: 14641

Callable will not work here, but Function will.

You could try instead this:

public static void iterateThroughQueue(Function<Deque<Integer>, Integer> function) {

    Deque<Integer> deq = new ArrayDeque<>();

    deq.add(1);
    deq.add(2);
    deq.add(3);

    for (int i = 0; i < 3; i++) {
        System.out.println(function.apply(deq));
    }
    System.out.println("size after iteration = "  + deq.size());
}

public static void main(String[] args) {
    iterateThroughQueue(Deque::pollFirst);
}

This prints:

1
2
3
size after iteration = 0

Upvotes: 2

Related Questions