0

I want to replace my lambda expression with a method reference. Following is my code snippet.

@FunctionalInterface
interface MessageProcessor<T, E extends Exception> {
    void process(T t) throws E;
}

and my class is

public class MessageHandler {
    public static Map<String, MessageProcessor<JsonElement, Exception>> map = new HashMap<>();
    map.put("create_key" , (jsonElement) -> MessageUtil.processCreate(jsonElement));
    map.put("update_key" , (jsonElement) -> MessageUtil.processUpdate(jsonElement));
    map.put("delete_key" , (jsonElement) -> MessageUtil.processDelete(jsonElement));
}

and my utility methods are

public static void processCreate(JsonElement jsonElement) throws Exception {
     // create logic
}

public static void processUpdate(JsonElement jsonElement) throws Exception {
     // update logic
}
public static void processDelete(JsonElement jsonElement) throws Exception {
    // delete logic
}

Now I want to replace the lambda expression with a method reference. How can I replace?

Holger
  • 285,553
  • 42
  • 434
  • 765
Ashok Kumar
  • 105
  • 2
  • 8
  • 4
    `map.put("create_key" , MessageUtil::processCreate);`? – Lei Yang Apr 06 '22 at 13:41
  • Why? See [this](https://stackoverflow.com/a/24493905/1552534) – WJS Apr 06 '22 at 14:00
  • 1
    Or just let your IDE do the conversion. – Holger Apr 06 '22 at 14:00
  • @WJS Method references are commonly agreed to be, most of the time, more compact and readable than using lambdas, and are therefore preferred. – Ashok Kumar Apr 06 '22 at 14:55
  • I disagree (did you see the question I cited?) With your method reference I have no idea what it takes as an argument. With the lambda, I know it takes a JSON element. As long as the parameters are properly named, lambda's aid the documentation process. But I also use method references quite a bit. Especially in streams where the arguments to the references are better understood or obvious. They should be used when it makes sense to do so. In your case, I would use lambdas. – WJS Apr 06 '22 at 15:15

0 Answers0