从Java中的键值对构建映射

Rom*_*man 2 java collections map guava

可能重复:
HashMap的构建器

是否有任何实用程序类允许以方便和可读的方式从多个键值对创建Map?

我认为guava应该包含一些东西,但我找不到任何必要的功能.

我想要的是这样的:

MapBuilder.newHashMap()
  .with("key1", 10)
  .with("key2", 20)
  .with("key3", 30)
  .build();
Run Code Online (Sandbox Code Playgroud)

PS我也知道双支撑方式(new HashMap<>() {{ put(..); put(..); }}),但我发现它既不可读也不方便.

JB *_*zet 6

怎么了?

Map<String, Integer> map = new HashMap<>();
map.put("key1", 10);
map.put("key2", 20);
map.put("key3", 30);
Run Code Online (Sandbox Code Playgroud)

这对我来说看起来很可读,而且我看不到你从MapBuilder中获得了什么.无论如何,这样的MapBuilder并不难实现.


Rob*_*ert 5

为什么不滚动自己?

public class MapBuilder<K,V> {

    private Map<K,V> map;

    public static <K,V> MapBuilder<K,V> newHashMap(){
            return new MapBuilder<K,V>(new HashMap<K,V>());
    }

    public MapBuilder(Map<K,V> map) {
        this.map = map;
    }

    public MapBuilder<K,V> with(K key, V value){
        map.put(key, value);
        return this;
    }

    public Map<K,V> build(){
        return map;
    }

}
Run Code Online (Sandbox Code Playgroud)