jeffsia jeffsia - 3 months ago 19
Groovy Question

Converting java lambda to pre java 1.8 function

I am using Babbler to write an XMPP soft client for doing load testing.

In the API documentation Babbler documentation, it mentions adding listeners to intercept incoming messages. However, the example code is written in lambda form.

// Listen for messages
xmppClient.addInboundMessageListener(e -> {
Message message = e.getMessage();
// Handle inbound message.
});


I need help converting this to Java 1.7 function since our load generation tool (nGrinder) does not support lambda syntax.

Answer
// Listen for messages
xmppClient.addInboundMessageListener(new Consumer<MessageEvent>() {

    public void accept(MessageEvent e) { 
        Message message = e.getMessage();
        // Handle inbound message.
    }
});

You can also avoid creating a new Consumer instance every time you invoke a certain lambda function by storing it in an instance variable.

private Consumer<MessageEvent> inboundMessageListener;

public void initialize() {
    inboundMessageListener = new Consumer<MessageEvent>() {

        public void accept(MessageEvent e) { 
            Message message = e.getMessage();
            // Handle inbound message.
        }
    };

    xmppClient.addInboundMessageListener(inboundMessageListener);
}