HashMap 批量添加

需要初始化一个常量HashMap,并希望在一行语句中完成。避免像这样的事情:

  hashMap.put("One", new Integer(1)); // adding value into HashMap
  hashMap.put("Two", new Integer(2));
  hashMap.put("Three", new Integer(3));

解决方法:

1、谷歌的ImmutableMap

import com.google.common.collect.ImmutableMap;

// For up to five entries, use .of()
Map<String, Integer> littleMap = ImmutableMap.of(
    "One", Integer.valueOf(1),
    "Two", Integer.valueOf(2),
    "Three", Integer.valueOf(3)
);

// For more than five entries, use .builder()
Map<String, Integer> bigMap = ImmutableMap.<String, Integer>builder()
    .put("One", Integer.valueOf(1))
    .put("Two", Integer.valueOf(2))
    .put("Three", Integer.valueOf(3))
    .put("Four", Integer.valueOf(4))
    .put("Five", Integer.valueOf(5))
    .put("Six", Integer.valueOf(6))
    .build();

2、从Java9开始,可以使用Map.of(...)

Map<String, Integer> immutableMap = Map.of("One", 1,
                                           "Two", 2,
                                           "Three", 3);

3、自己实现

import java.util.HashMap;
//实现处理类
public class QuickHash extends HashMap<String,String> {
    public QuickHash(String...KeyValuePairs) {
        super(KeyValuePairs.length/2);
        for(int i=0;i<KeyValuePairs.length;i+=2)
            put(KeyValuePairs[i], KeyValuePairs[i+1]);
    }
}

//使用它
Map<String, String> Foo=QuickHash(
    "a", "1",
    "b", "2"
);
posted @ 2023-02-08 11:21  super_龙  阅读(601)  评论(0编辑  收藏  举报