Categories

Java Map literals, continued

Here is a better map literal, since it keeps keys close to their values :

public class Literals {
     // ...
     public static <S, T> MapBuilder<S, T> map(S key, T value) {
         return new MapBuilder<S, T>().map(key, value);
     }

     public static class MapBuilder<S, T> extends HashMap<S, T> {
         public MapBuilder() {
         }

         public MapBuilder<S, T> map(S key, T value) {
             put(key, value);
             return this;
         }
     }
}

// Example usage :
import static Literals.map;
Map<String,Integer> example = map("hello",1).map("world",2).map("!",3);

Laisser un commentaire

blog comments powered by Disqus