Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

3.2. Parameters of Lambda Expressions

When you ask your user to supply a comparator, it is pretty obvious that the comparator has two arguments—the values to be compared.

   (s, t) -> Integer.compare(s.length(), t.length())); // Compare strings s and t

Now consider a different example. This method repeats an action multiple times:

public static void repeat(int n, IntConsumer action) {
   for (int i = 0; i < n; i++) action.accept(i); 

Why an IntConsumer and not a Runnable? We tell the action in which iteration it occurs, which might be useful information. The action needs to capture that input in a parameter

repeat(10, i -> System.out.println("Countdown: " + (9 - i)));

Another example is an event handler

button.setOnAction(event -> action);

The event object carries information that the action may need.

In general, you want to design your algorithm so that it passes any required information as arguments. For example, when editing an image, it makes sense to have the user supply a function that computes the color for a pixel. Such a function might need to know not just the current color, but also where the pixel is in the image, or what the neighboring pixels are.

However, if these arguments are rarely needed, consider supplying a second version that doesn’t force users into accepting unwanted arguments:

public static void repeat(int n, Runnable action) {
   for (int i = 0; i < n; i++) action.run(); 

This version can be called as

repeat(10, () -> System.out.println("Hello, World!"));
  • + Share This
  • 🔖 Save To Your Account