guava常见用法整理(不定期更新)

guava

  1. 集合
    1. 不变Collection的创建
      1. ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
        ImmutableSet<String> iSet = ImmutableSet.of("e1", "e2");
        ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");
    2. 创建map集合(key=String,value=list)
      1. Multimap<String,Integer> map = ArrayListMultimap.create();         
        map.put("aa", 1);
        map.put("aa", 2);
        System.out.println(map.get("aa"));  //[1, 2]
    3. MultiSet: 无序+可重复
      1. Multiset<String> set = HashMultiset.create();
    4. Multimap: key-value  key可以重复 
      1. Multimap<String, String> teachers = ArrayListMultimap.create();
    5. BiMap: 双向Map(Bidirectional Map) 键与值都不能重复
       
      1. BiMap<String, String> biMap = HashBiMap.create();
    6. Table: 双键的Map Map--> Table-->rowKey+columnKey+value
      1. Table<String, String, Integer> tables = HashBasedTable.create();
    7. 将集合转换为特定规则的字符串
      1. List<String> list = new ArrayList<String>();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        String result = Joiner.on("-").join(list);
    8. 把 map 集合转换为特定规则的字符串
      1. Map<String, Integer> map = Maps.newHashMap();
        map.put("xiaoming", 12);
        map.put("xiaohong",13);
        String result = Joiner.on(",").withKeyValueSeparator("=").join(map);
         
    9. 将 String 转换为特定的集合
      1. String str = "1-2-3-4-5-6";
        List<String> list = Splitter.on("-").splitToList(str);
      2. String str = "xiaoming=11,xiaohong=23";
        Map<String,String> map = Splitter.on(",").withKeyValueSeparator("=").split(str);
      3. String str = "1-2-3-4-  5-  6   "; 
        List<String> list = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(str);
        System.out.println(list);
    10. 多个字符切割,或者特定的正则分隔
      1. String input = "aa.dd,,ff,,.";
        List<String> result = Splitter.onPattern("[.|,]").omitEmptyStrings().splitToList(input);
      2. // 判断匹配结果
        boolean result = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matches('K'); //true

        // 保留数字文本  CharMatcher.digit() 已过时   retain 保留
        //String s1 = CharMatcher.digit().retainFrom("abc 123 efg"); //123
        String s1 = CharMatcher.inRange('0', '9').retainFrom("abc 123 efg"); // 123

        // 删除数字文本  remove 删除
        // String s2 = CharMatcher.digit().removeFrom("abc 123 efg");    //abc  efg
        String s2 = CharMatcher.inRange('0', '9').removeFrom("abc 123 efg"); // abc  efg

         
    11. 集合的过滤
      1. ImmutableList<String> names = ImmutableList.of("begin", "code", "Guava", "Java");
        Iterable<String> fitered = Iterables.filter(names, Predicates.or(Predicates.equalTo("Guava"), Predicates.equalTo("Java")));
        System.out.println(fitered);
         
      2. //自定义过滤条件   使用自定义回调方法对Map的每个Value进行操作
        ImmutableMap<String, Integer> m = ImmutableMap.of("begin", 12, "code", 15);
                // Function<F, T> F表示apply()方法input的类型,T表示apply()方法返回类型
                Map<String, Integer> m2 = Maps.transformValues(m, new Function<Integer, Integer>() {
                    public Integer apply(Integer input) {
                          if(input>12){
                                 return input;
                          }else{
                                 return input+1;
                          }
                    }
                });
        System.out.println(m2);   //{begin=13, code=15}
    12. set 的交集,并集,差集
      1. HashSet setA = newHashSet(1, 2, 3, 4, 5); 
        HashSet setB = newHashSet(4, 5, 6, 7, 8); 
          
        SetView union = Sets.union(setA, setB);   
        System.out.println("union:"); 
        for (Integer integer : union) 
            System.out.println(integer);           //union 并集:12345867
          
        SetView difference = Sets.difference(setA, setB); 
        System.out.println("difference:"); 
        for (Integer integer : difference) 
            System.out.println(integer);        //difference 差集:123
          
        SetView intersection = Sets.intersection(setA, setB); 
        System.out.println("intersection:"); 
        for (Integer integer : intersection) 
            System.out.println(integer);  //intersection 交集:45
    13. map 的交集,并集,差集
      1. HashMap<String, Integer> mapA = Maps.newHashMap();
        mapA.put("a", 1);mapA.put("b", 2);mapA.put("c", 3);

        HashMap<String, Integer> mapB = Maps.newHashMap();
        mapB.put("b", 20);mapB.put("c", 3);mapB.put("d", 4);

        MapDifference differenceMap = Maps.difference(mapA, mapB);
        differenceMap.areEqual();
        Map entriesDiffering = differenceMap.entriesDiffering();
        Map entriesOnlyLeft = differenceMap.entriesOnlyOnLeft();
        Map entriesOnlyRight = differenceMap.entriesOnlyOnRight();
        Map entriesInCommon = differenceMap.entriesInCommon();

        System.out.println(entriesDiffering);   // {b=(2, 20)}
        System.out.println(entriesOnlyLeft);    // {a=1}
        System.out.println(entriesOnlyRight);   // {d=4}
        System.out.println(entriesInCommon);    // {c=3}
  2. 检查参数
    1. if(!Strings.isNullOrEmpty(str))
    2. Preconditions.checkArgument(count > 0, "must be positive: %s", count); 
  3. MoreObjects
    1. Person person = new Person("aa",11);
      String str = MoreObjects.toStringHelper("Person").add("age", person.getAge()).toString();
      System.out.println(str); 
      //输出Person{age=11}
  4. 强大的 Ordering 排序器
    1. natural()     对可排序类型做自然排序,如数字按大小,日期按先后排序
      usingToString()     按对象的字符串形式做字典排序[lexicographical ordering]
      from(Comparator) 把给定的Comparator转化为排序器
      reverse()    获取语义相反的排序器
      nullsFirst()  使用当前排序器,但额外把null值排到最前面。
      nullsLast()   使用当前排序器,但额外把null值排到最后面。
      compound(Comparator)  合成另一个比较器,以处理当前排序器中的相等情况。
      lexicographical()    基于处理类型T的排序器,返回该类型的可迭代对象Iterable<T>的排序器。
      onResultOf(Function) 对集合中元素调用Function,再按返回值用当前排序器排序。
      1. Person person = new Person("aa", 144444); //String name  ,Integer age
        Person ps = new Person("bb", 13);
        Ordering<Person> byOrdering = Ordering.natural().nullsFirst().onResultOf(new Function<Person, Integer>() {
            public Integer apply(Person person) {
                return person.age;
            }
        });
        byOrdering.compare(person, ps);
        System.out.println(byOrdering.compare(person, ps)); // -1
  5. 计算中间代码的运行时间
    1. Stopwatch stopwatch = Stopwatch.createStarted();
      for(int i=0; i<100000; i++){
        // do some thing
      }
      long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
      System.out.println(nanos);
  6. 文件操作
    1. File file = new File("test.txt");
      List<String> list = null;
      try {
        list = Files.readLines(file, Charsets.UTF_8);
      } catch (Exception e) {
      }

      Files.copy(from,to);  //复制文件
      Files.deleteDirectoryContents(File directory); //删除文件夹下的内容(包括文件与子文件夹) 
      Files.deleteRecursively(File file); //删除文件或者文件夹 
      Files.move(File from, File to); //移动文件
      URL url = Resources.getResource("abc.xml"); //获取classpath根下的abc.xml文件url
  7. guava 缓存
    1. CacheLoader
      1. LoadingCache<String,String> cahceBuilder=CacheBuilder
                         .newBuilder()
                         .build(new CacheLoader<String, String>(){
                             @Override
                             public String load(String key) throws Exception {       
                                 String strProValue="hello "+key+"!";               
                                 return strProValue;
                             }
                         });       
        System.out.println(cahceBuilder.apply("begincode"));  //hello begincode!
        System.out.println(cahceBuilder.get("begincode")); //hello begincode!
        System.out.println(cahceBuilder.get("wen")); //hello wen!
        System.out.println(cahceBuilder.apply("wen")); //hello wen!
        System.out.println(cahceBuilder.apply("da"));//hello da!
        cahceBuilder.put("begin", "code");
        System.out.println(cahceBuilder.get("begin")); //code
    2. callback
      1. Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build(); 
                  String resultVal = cache.get("code", new Callable<String>() { 
                      public String call() { 
                          String strProValue="begin "+"code"+"!";               
                          return strProValue;
                      } 
                  }); 
         System.out.println("value : " + resultVal); //value : begin code!
  8. 参考
    1. https://juejin.cn/post/6844903667498221581#heading-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值