Java集合 使用Guava操做集合类

这是在一个课程中,看到了做者用 HashMap map = Maps.newHashMap()这种写法建立map对象感到很新颖,后来查到是用了google的Guava核心库,主要是使得代码更优美,易维护,易读,从大量的底层冗杂的代码中解脱。java

引入guava

<dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>19.0</version>
            </dependency>

下面就能够愉快地使用了:ui

HashMap m = Maps.newHashMap();
        m.put("A","B");
        m.put("C","D");
        System.out.println( m.get("A")); //B
        System.out.println( m.get("C")); //D

        List list = Lists.newArrayList();
        list.add(1);
        list.add(2);
        System.out.println(list.get(0));//1
        System.out.println(list.get(1));//2

直接使用Maps.newHashMap来建立map集合等,有人会问这和使用原生java有什么不一样?google

查看源码,发现并无什么不一样,guava也只是作了封装,底层仍是调用jdk的。spa

 guava操做集合类还有一个重要的用法就是建立不可变的集合,使用继承或者实现List或Map的Immutable类,code

如ImmutableList,ImmutableMap,ImmutableSet等。对象

咱们知道能够使用Collections.unmodifiableList()来将集合变为不可改变类,但这种方法并很差,具体能够去查查资料。blog

使用guava的这种方式是更好的选择,其方式也很简单以下:继承

ImmutableList<Integer> of = ImmutableList.of(1,2,3,4);

        ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");

固然,这样看起来不太好看,有能够使用下面这种方式(推荐):get

ImmutableList list2 = new ImmutableList.Builder<Integer>()
                .add(1)
                .add(2)
                .add(3)
                .build();

        ImmutableMap<Integer, String> immutaleMap2 = new ImmutableMap.Builder<Integer, String>()
                .put(0,"day")
                .put(1,"night")
                .build();

若有不正确的地方,欢迎指正!源码

相关文章
相关标签/搜索