zoukankan      html  css  js  c++  java
  • Google Guava v11 Collections示例

    Guava中文是石榴的意思,该项目是 Google 的一个开源项目,包含许多 Google 核心的 Java 常用库。目前主要包含:

    • com.google.common.annotations
    • com.google.common.base
    • com.google.common.cache
    • com.google.common.collect
    • com.google.common.eventbus
    • com.google.common.io
    • com.google.common.net
    • com.google.common.primitives
    • com.google.common.util.concurrent

    这里先介绍一下最常用的com.google.common.collect包中的最常用的一些API,仅仅讨论一下API的使用方法,没有讨论到实现细节。

         1:Collections的构造方法

    我们平时直接创建Collections对象的方法一般都是用new关键字,有泛型的情况下看起来会比较长:

    Map<String , Map<String , String>> see = new HashMap<String, Map<String,String>>();

    在java7中,这个初始化做了简化:

    Map<String , Map<String , String>> see = new HashMap<>();

    可以通过Guava的API来这样写:

    Map<String , Map<String , String>> see = Maps.newHashMap();

    得到一个有size的Map:

    Map<String , Map<String , String>> see = Maps.newHashMapWithExpectedSize(32);

    在JDK的collection类型,在Guava中都可以找到相关的static的构造方法,例如:Lists , Sets , Maps , Queues 。新的colleciont类型提供了直接构造的方法,例如:HashMultimap<String, String> multiMap = HashMultimap.create();

        2:有限功能的函数式编程

    介绍2个重要的接口:

    com.google.common.base.Function : 根据输入值来得到输出值

    com.google.common.base.Predicate : 根据输入值得到 true 或者 false

    拿Collections2中有2个函数式编程的接口:filter , transform ,例如 :在Collection<Integer>中过滤大于某数的内容:

    Collection<Integer> filterList = Collections2.filter(collections

         , new Predicate<Integer>(){

                      @Override

                      public boolean apply(Integer input) {

                            if(input > 4)

                                  return false;

                            else

                                  return true;

                      }

    });

    把Lis<Integer>中的Integer类型转换为String , 并添加test作为后缀字符:

    List<String> c2 = Lists.transform(list, new Function<Integer , String>(){

                      @Override

                      public String apply(Integer input) {

                            return String.valueOf(input) + "test";

                      }            

    });

    需要说明的是每次调用返回都是新的对象,同时操作过程不是线程安全的。

     

         3:Multimap and BiMap

    Map中一个key只能有一个,后续put进去的内容会覆盖前面的内容,有些业务需要有相同的key,但是有不同的内容,Guava中提供了

    Multimaps 来解决这个问题。

                Multimap<String, String> prosons = HashMultimap.create();

                prosons.put("longhao", "hubei");

                prosons.put("lilei" , "henan");

                prosons.put("longhao", "shanxi");

                prosons.put("liuxia", "beijing");

                prosons.put("lilei", "hainan");

                Iterator<String> it = prosons.get("longhao").iterator();

                while(it.hasNext()){

                      System.out.println(it.next());

                }

    BiMap可以有相同的key,但是不能有相同的value,如果不同的key设置了相同的value,则会抛出IllegalArgumentException异常,可以通过inverse()来反转kv,values()来获取value的set。

    public void biMapShouldOnlyHaveUniqueValues() {

         BiMap<Integer, String> biMap = HashBiMap.create();

         biMap.put(1, "a");

         biMap.put(2, "b");

         biMap.put(3, "a"); //argh! an exception

    }

         4:tables

    给出一个columns, rows , values, 这个API和Map<K , Map<K , V>>形式差不多,多了一些封装。例子:

    static void tables(){

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

                user.put(1, "longhao", 29);

                user.put(1, "shuaige", 29);

                user.put(2, "xiaomi", 1);

                user.put(3, "soso", 3);

                System.out.println(user.containsColumn("soso"));//true

                System.out.println(user.containsColumn("3"));//false

                System.out.println(user.contains(1, "xiaomi"));//false

                System.out.println(user.contains(1, "meinv"));//true

                System.out.println(user.row(1));//{shuaige=29, longhao=29}

    }

         5:更简洁的判断

    使用Preconditions中的方法来判断是否为空等操作,这个操作和spring,apache common-lang中的API类似

    import static com.google.common.base.Preconditions.checkArgument;

    import static com.google.common.base.Preconditions.checkNotNull;

    static void checkParam(String name , Integer passwd){

                checkNotNull(name , passwd);

                checkArgument("" != name , passwd > 0);

    }

    Common-lang,spring中的方法需要逐个调用。而Guava中支持。

         6:约束

    对Collection中的新加入元素做约束,只有符合条件的元素才能够被添加到Collection中,可以使用Constraint类来操作。

    示例代码:

    import static com.google.common.collect.Constraints.constrainedList;

    static void constraintExam(){

                Constraint<String> chkListStr = new Constraint<String>(){

                      @Override

                      public String checkElement(String element) {

                            if(element.startsWith("h")){

                                  throw new IllegalArgumentException("不允许有h开头的内容");

                            }

                            return element;

                      }            

                };

                List<String> list = Lists.newArrayList("li","hao","a");

                List<String> conList = constrainedList(list, chkListStr);

                conList.add("soso");

                conList.add("hqb");// throw IllegalArgumentException

                for(String str : list){

                      System.out.println(str);

                }

    }

  • 相关阅读:
    如何使用第三方webservice
    SQL零星技术点:SQL中转换money类型数值转换为字符串问题
    P2664 树上颜色统计 点分治 虚树 树上差分 树上莫队
    SPOJ 1825 经过不超过K个黑点的树上最长路径 点分治
    P4149 距离为K的点对(最少边数) n=200000 点分治
    P2634 树上路径长度为3的倍数的点对数 点分治
    P3806 离线多次询问 树上距离为K的点对是否存在 点分治
    POJ 1741 单次询问树上距离<=K的点对数 点分治
    BZOJ 1016 生成树计数
    BZOJ 1015 并查集&连通块
  • 原文地址:https://www.cnblogs.com/PatrickLee/p/2637674.html
Copyright © 2011-2022 走看看