Guava扩展工具包

Guava扩展工具包

Guava包主要包括四部分:不可便集合(ImmutableCollections)、多值Map、Table表和集合工具类。

不可变集合

         不可变集合包括ImmutableList、ImmutableMap、ImmutableSet、ImmutableSortedMap、ImmutableSortedSet等,它比不可修改集合(UnmodifiableCollections)更容易使用,效率更高,而且占用的内存更少。实例如下:

        

        //2. 不可变对象,of 构造

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

        ImmutableMap<String, Integer> mapImmutableInt = ImmutableMap.of("1", 1, "2", 2, "3", 3);

        ImmutableSet<String> imutableSet = ImmutableSet.of("a", "b", "c");

        //2.2 排序的不可变集合

        ImmutableSortedMap<Integer, String> immutableSortedMap = ImmutableSortedMap.of(1, "1", 4, "4", 3, "3", 2, "2");

        System.out.println("immutableSortedMap=" + Joiner.on(",").withKeyValueSeparator("对应").join(immutableSortedMap));

        ImmutableSortedSet<String> immutableSortedSet = ImmutableSortedSet.of("4", "3", "2");

        //2.3  双向map 

        ImmutableBiMap<Integer,String> immutableBiMap = ImmutableBiMap.of(1,"a",2,"b",3,"c");

         其中的of方法有多个重载,其目的就是为了便于在初始化的时候直接生成一个不可变集合。

多值Map

         多值Map比较简单,在JDK中,Map中的一个键对应一个值,在Put一个键值对时,如果键重复了,则会覆盖原有的值,在大多数情况下这比较符合实际应用,但有的时候确实会存在一个键对应多个值得情况,比如我们的通讯录,一个人可能会对应两个或三个号码,此时使用JDK的Map就有点麻烦了。在这种情况下,使用Guava的Multimap可以很好地解决问题:

        

        //11. 多值Map:包含重复值的map,取代Map<String,List<String>>

        ListMultimap<Integer, String> multimap = ArrayListMultimap.create();

        multimap.put(1, "a");

        multimap.put(1, "b");

        multimap.put(2, "c");

        for (Map.Entry entry : multimap.entries()) {

            System.out.println("entry.key=" + entry.getKey());

            System.out.println("entry.value=" + entry.getValue());

        }

        System.out.println(multimap.get(1));    //[a,b]

        System.out.println(multimap.keys());    //[1 x 2, 2]

        System.out.println(multimap.keys().size());    //3

        System.out.println(multimap.values());    //[a, b, c]

        System.out.println(multimap.values().size());    //3

        System.out.println(multimap.size());    //3

 

Table表

         在GIS中,我们经常会把一个地点标注在一个坐标上,比如把上海人民广场标注在北纬31.23,东经121.48的位置上,也就是说只要给出了准确的经度和纬度就可以进行精确的定位——两个键决定一个值,这在Guava中可以使用Table来表示的,如:

        //12.table表:   两个坐标的map

        Table<Integer, Integer, String> table = HashBasedTable.create();

        table.put(1, 1, "zhangsan");

        table.put(1, 2, "lisi");

        table.put(2, 2, "wangwu");

        table.put(2, 2, "zhaoliu");

        Map<Integer, String> rowMap = table.row(1); //得到行集合

        int max = Collections.max(rowMap.keySet());

        String aTableValue = table.get(1, 1);

        System.out.println("坐标为1,1的值是:" + aTableValue);

        for (Map.Entry entry : rowMap.entrySet()) {

            System.out.println("entry.key=" + entry.getKey());

            System.out.println("entry.value=" + entry.getValue());

        }

 

集合工具类:

Guava的集合工具类分的比较细,比如Lists,Maps,Sets分别对应的是List、Map、Set的工具类。

List:拆分,翻转,批量转换

        //8.  List 使用:拆分,翻转,批量转换

        List<Integer> lists = Lists.newArrayList(1, 2, 3, 4, 5,6);

        List<List<Integer>> partitionLists = Lists.partition(lists, 3); //按照长度为3的次序拆分list

        List<Integer> listsReverse = Lists.reverse(lists);

        List<Double> transFormList = Lists.transform(lists, new Function<Integer, Double>() {

            public Double apply(@Nullable Integer input) {

                return Math.pow(input, 2);

            }

        });

         System.out.println("partitionLists = " + Joiner.on(",").join(partitionLists));

         System.out.println("listsReverse = " + Joiner.on(",").join(listsReverse));

         System.out.println("transFormList = " + Joiner.on(",").join(transFormList));

 

      Map:Map的和并交叉,过滤,批量转换等

        //10.Map的用法,

        // 10.1 和并交叉

        Map<String, Integer> mapA = ImmutableMap.of("a", 1, "b", 2, "c", 4);

        Map<String, Integer> mapB = ImmutableMap.of("d", 1, "b", 2, "c", 3);

        MapDifference<String, Integer> differenceMap = Maps.difference(mapA, mapB);

//        for(Map.Entry entry :differenceMap.entriesDiffering().entrySet()) {   //相当于mapAmapBkey相等,但是value不相等的集合

//        for(Map.Entry entry :differenceMap.entriesInCommon().entrySet()) {   //相当于mapAmapB的交集,b2

        for (Map.Entry entry : differenceMap.entriesOnlyOnRight().entrySet()) {  //相当于mapBmapA的差集,对比key,留mapB的元素:d:1

//        for(Map.Entry entry :differenceMap.entriesOnlyOnLeft().entrySet()) {   //相当于mapAmapB的差集,对比key,留mapA的元素:a:1

            System.out.println("entry.key=" + entry.getKey());

            System.out.println("entry.value=" + entry.getValue());

        }

        //10.2.过滤,所有value>2的键值对

        Map<String, Integer> filterMap = Maps.filterValues(mapA, new Predicate<Integer>() {

            public boolean apply(@Nullable Integer input) {

                return input > 2;

            }

        });

        System.out.println("过滤值大于2的map=" + Joiner.on(",").withKeyValueSeparator("是").join(filterMap));

 

        //10.3 批量转换,

        //定义一个函数,把value值取平方

        Function<Integer, Double> pow = new Function<Integer, Double>() {

            public Double apply(@Nullable Integer input) {

                return Math.pow(input, 2);  

            }

        };

        Map<String, Double> transFormMap = Maps.transformValues(mapB, pow);

        System.out.println("map的value批量处理=" + Joiner.on(",").withKeyValueSeparator("是").join(transFormMap));

Set:set的并集、交集、差集

        //9.集合的交集、并集、差集

        HashSet<Integer> setA = Sets.newHashSet(1, 2, 3, 4, 5);

        HashSet<Integer> setB = Sets.newHashSet(4, 5, 6, 7, 8);

 

        //并集

        Sets.SetView<Integer> union = Sets.union(setA, setB);

        System.out.println("union:");

        for (Integer integer : union) {

            System.out.println(integer);

        }

        //差集

        Sets.SetView<Integer> difference = Sets.difference(setA, setB);

        System.out.println("difference:" + Joiner.on(",").join(difference));

        //交集

        Sets.SetView<Integer> intersection = Sets.intersection(setA, setB);

        System.out.println("intersection:" + Joiner.on(",").join(intersection));

 

字符串操作

         Guava提供了两个非常好用的字符串操作工具:joiner连接器和Spliter拆分器。

Joiner:不仅可以连接字符,还可以连接多个对象,包括list,map等

        String[] strs = new String[]{"a", "b", "c", "f", "", "d", null};

        String noNa = Joiner.on(",").useForNull("NA").join(strs);//用“NA”替代null

        System.out.println("no Na=" + noNa);    //no Na=a,b,c,f,,d,NA

        String noNull = Joiner.on(",").skipNulls().join(strs);  //过滤null

        System.out.println("no Null=" + noNull); //no Null=a,b,c,f,,d

 

        //分割mapkeyvalue,把keyvalue连起来输出,比直接遍历输出Map方便了很多

        ImmutableMap<Integer, String> immutableMap = ImmutableMap.of(1, "zhangsan", 2, "lisi", 3, "wangwu");

        String multimapValue = Joiner.on(",").withKeyValueSeparator("是").join(immutableMap);

        System.out.println("multimap = " + multimapValue); //1是zhangsan,2是lisi,3是wangwu

Spliter:做字符串拆分,使用比较简单

        String s = "a,b,, ,c,";

        Iterable<String> strings = Splitter.on(",").omitEmptyStrings().trimResults().split(s);//过滤空串

        for (String word : strings) {

            System.out.println("word=" + word);

        }

        //按行拆分,比如进行格式化的时候打印,一行固定打印n个字符

        for(String word : Splitter.fixedLength(2).split(s)) {

             System.out.println("fixedLength,word=" + word);

        }

 

基本类型工具

         基本类型工具在primitives包中,是以基本类型名+s的方式命名的,如Ints是int的工具类,Doubles是double的工具类,注意这些都是针对基本类型的,而不是针对包装类型的。

        //7.基本类型工具类,如Ints是int的工具类,Doubles是double的工具类

        int isBig = Longs.compare(2l, 3l);

        int intCompare = Ints.compare(2, 3);

        int[] ints = {10, 9, 30, 8, 1};

        System.out.println("max=" + Ints.max(ints));

        System.out.println("min=" + Ints.min(ints));

        List<Integer> integerList = Ints.asList(ints);//asList转换为List

        System.out.println("integerList=" + Joiner.on(",").join(integerList));

        System.out.println("joins=" + Ints.join(",", ints));  //join方法转为String

        int[] intsCopy = Ints.toArray(integerList);  //toArray转换为Array

 

其他参考:

http://www.cnblogs.com/snidget/archive/2013/02/05/2893344.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值