ImmutableMap是不可变的,线程安全的;它可以创建一些常量的映射键值对;他提供了很多的组合键值对的方法,源码中使用了一个静态内部类来组装构建ImmutableMap,静态内部类作为外部类的辅助构建ImmutableMap,内部使用final声明了一个ArrayList变量。

  public static class Builder<K, V>{
     final ArrayList<Map.Entry<K, V>> entries = Lists.newArrayList();

    public Builder() {}

    public Builder<K, V> put(K key, V value)
    {
      this.entries.add(ImmutableMap.entryOf(key, value));
      return this;
    }

    public Builder<K, V> put(Map.Entry<? extends K, ? extends V> entry)
    {
      K key = entry.getKey();
      V value = entry.getValue();
      if ((entry instanceof ImmutableEntry)) {
        Preconditions.checkNotNull(key);
        Preconditions.checkNotNull(value);

        Map.Entry<K, V> immutableEntry = entry;
        this.entries.add(immutableEntry);
      }
      else
      {
        this.entries.add(ImmutableMap.entryOf(key, value));
      }
      return this;
    }

    public Builder<K, V> putAll(Map<? extends K, ? extends V> map)
    {
      this.entries.ensureCapacity(this.entries.size() + map.size());
      for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
        put(entry.getKey(), entry.getValue());
      }
      return this;
    }

    public ImmutableMap<K, V> build()
    {
      return fromEntryList(this.entries);
    }

    private static <K, V> ImmutableMap<K, V> fromEntryList(List<Map.Entry<K, V>> entries)
    {
      int size = entries.size();
      switch (size) {
      case 0: 
        return ImmutableMap.of();
      case 1: 
        return new SingletonImmutableBiMap((Map.Entry)Iterables.getOnlyElement(entries));
      }
      Map.Entry<?, ?>[] entryArray = (Map.Entry[])entries.toArray(new Map.Entry[entries.size()]);

      return new RegularImmutableMap(entryArray);
    }
  }

之前我们判断取值结果可以使用if else形式:

        int a = 1;
        if(a == 1) {
            System.out.println(a);
        } else {
            System.out.println(a);
        }

或者使用switch方式:

        int a = 1;
        switch (a) {
        case 1:
            System.out.println(a);
            break;
        case 2:
            System.out.println(a);
        default:
            System.out.println(a);
            break;
        }

现在可以使用ImmutableMap集合来组装键值对,这样的组合方式既简单又省去了大量多余的代码:

        ImmutableMap<String, Object> map = ImmutableMap .<String, Object>builder()
                                                                      .put("1", "1")
                                                                      .put("2", "2")
                                                                      .put("3", "3")
                                                                      .build();

        ImmutableMap<String, String> map1 = ImmutableMap .<String, String>of("1", "2");