LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Expressions Programs · Question 4

Button click listeners with Consumer lambdas in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Write a Button class that keeps a list of Consumer<String> listeners and notifies them on click; register lambdas and a method reference, then click twice.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

class Button {
    private final String label;
    private final List<Consumer<String>> listeners = new ArrayList<>();
    private int clicks;
    Button(String label) { this.label = label; }

    void onClick(Consumer<String> l) { listeners.add(l); }
    void click() { clicks++; listeners.forEach(l -> l.accept(label + "#" + clicks)); }
}

public class Main {
    static final List<String> AUDIT = new ArrayList<>();
    static void audit(String event) { AUDIT.add(event); }

    public static void main(String[] args) {
        Button save = new Button("Save");
        save.onClick(e -> System.out.println("saving... " + e));
        save.onClick(e -> { if (e.endsWith("#2")) System.out.println("double-click detected"); });
        save.onClick(Main::audit);
        save.click();
        save.click();
        System.out.println("audit " + AUDIT);
    }
}

Output Verified by compiling and running

saving... Save#1
saving... Save#2
double-click detected
audit [Save#1, Save#2]

Lambdas and method references are interchangeable listeners – this is how GUI and event frameworks use functional interfaces.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links