What does this lambda expression mean?

吴经毅 :

It looks like an anonymous class. I didn't find any article talk about this usage of lambdas.

   public Supplier<Map<Boolean, List<Integer>>> supplier() {
        return () -> new HashMap<>() { //todo what does this mean?
            {
                this.put(false, new ArrayList<>());
                this.put(true, new ArrayList<>());
            }
        };
    }
Jesper :

There are a number of different things going on here.

The method returns a Supplier<Map<...>>. The lambda expression () -> new HashMap<>() ... returns an instance of the interface Supplier which returns a HashMap.

Also, it doesn't return a plain HashMap; an anonymous subclass of HashMap is being created here because of the outer { ... }.

The inner { ... } is an instance initializer block which is used to put stuff in the HashMap (two entries with keys true and false and each an ArrayList as the value).

This is using the double-brace initialization trick. (That link points to a blogpost written by me that explains why I dislike that trick).

A better way to write this (if you're using Java 9 or newer) that doesn't use the double-brace initialization trick is like this:

public Supplier<Map<Boolean, List<Integer>>> supplier() {
    return () -> Map.of(
        false, new ArrayList<>(),
        true, new ArrayList<>());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322239&siteId=1