How to replace the listeners with anonymous classes in Java?

Solution 1:

You can anonymously implement the interface by opening a block after the new call:

listeners.add(new ClientRegistrationListener() {
   @Override
   public void onClientAdded(Client client) {
       System.out.println("Client added: " + client.getName());
   }
});

Or, even more elegantly, since ClientRegistrationListener is a functional interface (even though it's not annotated as one), you can anonymously implement it with a lambda expression:

listeners.add(client -> System.out.println("Client added: " + client.getName()));