Guava学习笔记

Guava 是谷歌开发的高效切简单的API 里面有大量的方法来提高我们平时的开发效率。本文是根据http://ifeve.com/google-guava/(并发编程网)的教学自己写的一些demo笔记

1.Optional

使用Optional除了赋予null语义,增加了可读性,最大的优点在于它是一种傻瓜式的防护。Optional迫使你积极思考引用缺失的情况,因为你必须显式地从Optional获取引用


    private static   void  optionalStudy(){
        String s1 = null;
        String s2 = "-";
        String s3 = "2";
        Optional<String> nullOption = Optional.fromNullable(s1);
        //创建指定引用的Optional实例,若引用为null则表示缺失
        Optional<String> Option2 = Optional.fromNullable(s2);
        //返回Optional所包含的引用,若引用缺失,则抛出java.lang.IllegalStateException
        String r1 = Option2.get();
        //返回Optional所包含的引用,若引用缺失,返回指定的值
        String r2 = nullOption.or("22");
        //返回Optional所包含的引用,若引用缺失,返回null
        String r3 = nullOption.orNull();
        // 如果Optional包含非null的引用(引用存在),返回true
        boolean r4 = nullOption.isPresent();

        System.out.println( Option2.or("22"));
    }

2.字符串 处理工具

private  static void stringUntil(){
        //joiner 连接器 将list转为String
        List<String> list = Lists.newArrayList("a", "b", "c",null);
        //useForNull  将null 转化未某个值
        String listTOString = Joiner.on(",").useForNull("22").join(list);
        //skipNulls 去除null
        String listTOString2 = Joiner.on(",").skipNulls().join(list);
        System.out.println(listTOString);


        ConcurrentMap<Integer, String> map = Maps.newConcurrentMap();
        map.put(1,"haha");
        map.put(2,"haha2");
        //withKeyValueSeparator key value 之间的分隔符
        String mapString = Joiner.on(",").withKeyValueSeparator(":").join(map);
        System.out.println(mapString);

        //splitter 拆分  trimResults去除空格  omitEmptyStrings去除拆分出来空的字符串
        String string1 = "1,2,3, 4 ,5,hh, ,";
        List<String> stringToList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(string1);
        System.out.println(stringToList);
        //按照长度分割
        List<String> stringToList2 = Splitter.fixedLength(3).splitToList(string1);
        System.out.println(stringToList2);



    }

3.前置条件

  //前置条件
    private  static void Precondition(){
        int i = 0;
        Integer i1=2;
        Preconditions.checkArgument(i>=0 ,"参数异常");
        Preconditions.checkNotNull(i1,"参数为空");
       // Preconditions.checkPositionIndex(0,1);
    }

4.排序器order

private  static void order(){

        ArrayList<Integer> list1 = Lists.newArrayList(5, 2, 3, 4, 5, 6, null);
        // Ordering.natural() 自然排序  nullsFirst 将null放在最前
        Collections.sort(list1,Ordering.natural().nullsFirst());
        //nullsLast 将null放在最后  reverse大到小排序
        Collections.sort(list1,Ordering.natural().reverse().nullsLast());
        System.out.println(list1);
        //是否是按照自然排序的
        boolean bool = Ordering.natural().isOrdered(list1);
        //greatestOf获取集合的前k个元素     leastOf 获取集合后k个元素 如果存在reverse 则相反
        List<Integer> list2 = Ordering.natural().nullsLast().greatestOf(list1, 5);


        System.out.println(list2);



        ArrayList<User> listTest = Lists.newArrayList(new User(2, "ljb"), new User(2, "ljb2"), new User(3, "ljb3"));
        // from 第一个比较器 如果相等在和 compound第二个比较比较强比较
        Ordering<User> order = Ordering.from(new User()).compound(new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return Ints.compare(o1.getName().length() ,o2.getName().length());
            }
        }).reverse();

        Collections.sort(listTest,  order);

        System.out.println(listTest);
        List<User> order2 = Ordering.from(new User()).compound(new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return Ints.compare(o1.getName().length(), o2.getName().length());
            }
        }).reverse().leastOf(listTest, 2);
        System.out.println(order2);

    }

5. 新集合类型(重要)

 private  static void multisetDemo(){
        HashMultiset<String> hashMultiset = HashMultiset.create();
        hashMultiset.addAll(Lists.newArrayList("a","b","c","d"));
        hashMultiset.add("a");
        hashMultiset.add("b");
        //count 计算出某个元素的个数
        int acount = hashMultiset.count("a");
        int ccount = hashMultiset.count("f");
        System.out.println(acount+"--"+ccount);
        //Multiset中不重复元素的集合,类型为Set
        Set<String> s = hashMultiset.elementSet();
        System.out.println(s);
        //集合元素*出现次数, 例子输出[a x 2, b x 2, c, d]
        Set<Multiset.Entry<String>> ss = hashMultiset.entrySet();
        System.out.println(ss);

        ArrayListMultimap<String, User> map2 = ArrayListMultimap.create();
        map2.put("ljb",new User(1,"ljb"));
        map2.put("ljb",new User(1,"ljb"));
        map2.put("ljb2",new User(1,"ljb2"));
        List<User> list = map2.get("ljb");
        System.out.println(map2);


        HashMultimap<String, User> hashmap = HashMultimap.create();
        hashmap.put("ljb",new User(1,"ljb"));
        hashmap.put("ljb",new User(2,"ljb"));
        hashmap.put("ljb2",new User(1,"ljb2"));
        Set<User> getmap = hashmap.get("ljb");
        Set<Map.Entry<String, User>> ent = hashmap.entries();
        //获取key值
        Set<String> keySet = hashmap.keySet();
        //获取key值*出现次数
        Multiset<String> keys = hashmap.keys();
        System.out.println(ent);
        System.out.println(keys);
        hashmap.remove("ljb",new User(1,"ljb"));
        System.out.println(hashmap);

    }

缓存

  private  static void cacheDemo() throws ExecutionException {

        Cache<String, Object> cache = CacheBuilder.newBuilder()
                //设置初始话容量
                .initialCapacity(10)
                // 最大缓存 100 个
                .maximumSize(1000)
                // 设置写缓存后 5 秒钟过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 设置缓存在30s内未范文则过期
                .expireAfterAccess(30,TimeUnit.SECONDS)
                //设置并发量 为10
                .concurrencyLevel(10)
                .build();
        cache.put("abc","213123");
        //获取key  如果没有则返回null
        Object cacheGet = cache.getIfPresent("abc");
        System.out.println(cacheGet)    ;
        // 获取缓存,当缓存不存在时,则通Callable进行加载并返回。该操作是原子
        Object ss = cache.get("ac", () -> {
            System.out.println("缓存没这个key");
            return "ac";
        });
        System.out.println(ss);

        //cacheloader 自发的加载缓存
        LoadingCache<Object, Object> cache2 = CacheBuilder.newBuilder()
                .maximumSize(100)
                .concurrencyLevel(10)
                .expireAfterWrite(5, TimeUnit.SECONDS)

                .build(new CacheLoader<Object, Object>() {
                    @Override
                    public Object load(Object key) throws Exception {
                        // 缓存加载逻辑
                        //返回key 值
                        return key;
                    }
                });
        /// 获取缓存,当缓存不存在时,会通过CacheLoader自动加载,该方法会抛出ExecutionException异常
        Object cacheGet2 = cache2.get("abc");
        //以不安全的方式获取缓存,当缓存不存在时,会通过CacheLoader自动加载,该方法不会抛出异常
        Object cacheGet3 = cache2.getUnchecked("a");
        System.out.println(cacheGet2);
        System.out.println(cacheGet3);

    }

你可能感兴趣的:(java,基础)