有时候我们想快速初始化一个list和map,但是又不想写成下面这种冗长的模式
private static final Map<Integer, String> priorityMap = new HashMap() { private static final long serialVersionUID = 1619653958196860773L; { put(1, "急"); put(2, "般"); put(3, "守"); } }; List<Integer> list=new ArrayList<>(); list.add(1); list.add(2); list.add(3);
有没有办法将我们从这种无聊的样例代码中解放出来,有!那就是guava
上pom
<!-- google java lib --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>17.0</version> </dependency>
有了它,我们就可以这样快速初始化list和map
/** * @Author : wangbin * @Date : 2021/6/25 14:24 * @Description: */ public class Test { public static void main(String[] args) { //不可变map,不能更新 ImmutableMap<String, Integer> of = ImmutableMap.of("a", 1, "b", 2, "c", 3); //可变map,可以更新 Map<String, Object> hashMap = Maps.newHashMap(of); hashMap.put("d",5); System.out.println(hashMap.get("d")); //可变list,可以添加元素 List<String> fo = Lists.newArrayList("a", "b", "c"); //不可变list List<Integer> integers = Arrays.asList(1, 2, 3); fo.add("d"); System.out.println(fo); } }