总结一份Guava常用的操作


/**
 * @author chenyi
 */
public class TestGroovy {

    /**
     * 可以存储多个相同kEY的数据.
     */
    @Test
    public void testHashMultimap(){
        //存储数据结构 {key1=[a1,a2],key2=[b1,b2]}
        HashMultimap<String,Integer> map = HashMultimap.create();
        map.put("lisa",20);
        map.put("lisa",12);
        map.put("tom",23);
        map.put("bob",34);
        map.put("selena",29);
        //result: {selena=[29], tom=[23], bob=[34], lisa=[20, 12]}
        System.out.println(map.toString());
        //result: [20, 12]
        System.out.println(map.get("lisa"));

    }

    /**
     * 笛卡尔集
     */
    @Test
    public void cartesianProcustTest(){
        List<String> list1 = Lists.newArrayList("a","b","c");
        List<String> list2 = Lists.newArrayList("d","e","f");
        List<String> list3 = Lists.newArrayList("1","2","3");
        //获取多个list的笛卡尔集
        // https://baike.baidu.com/item/%E7%AC%9B%E5%8D%A1%E5%B0%94%E9%9B%86/4542998?fr=aladdin
        List<List<String>> list = Lists.cartesianProduct(list1,list2,list3);
        //[[a, d, 1], [a, d, 2], [a, d, 3], [a, e, 1], [a, e, 2], [a, e, 3], [a, f, 1], [a, f, 2], [a, f, 3], [b, d, 1], [b, d, 2], [b, d, 3], [b, e, 1], [b, e, 2], [b, e, 3], [b, f, 1], [b, f, 2], [b, f, 3], [c, d, 1], [c, d, 2], [c, d, 3], [c, e, 1], [c, e, 2], [c, e, 3], [c, f, 1], [c, f, 2], [c, f, 3]]
        System.out.println(list);
    }


    /**
     *字符串拼接
     */
    @Test
    public void testJoinGavua(){
        String[] strs = new String[]{"1","2","a","b","c",null," ","d "};
        //数组拼接 去掉 null
        String join = Joiner.on("=").skipNulls().join(strs);
        //1=2=a=b=c= =d
        System.out.println(join);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1","value2");
        hashMap.put("key2","value2");
        hashMap.put("key3","value2");
        hashMap.put("key4","value2");
        //map 拼接
        String join1 = Joiner.on("\""+",\"").withKeyValueSeparator("\""+":\"").join(hashMap);
        //key1":"value2","key2":"value2","key3":"value2","key4":"value2
        System.out.println(join1);
    }

    @Test
    public void testSpliter(){
        String begin = "a,b ,c ,null, ga,   ";
        //逗号分隔
        List<String> notTrim = Splitter.on(",").splitToList(begin);
        // [a, b , c , null,  ga,    ]
        System.out.println(notTrim);
        //逗号分隔 去掉空格
        List<String> trim = Splitter.on(",").trimResults().splitToList(begin);
        //[a, b, c, null, ga, ]
        System.out.println(trim);
        //逗号分隔 去掉空格 然后去掉空数
        List<String> strings = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(begin);
        //[a, b, c, null, ga]
        System.out.println(strings);
    }

    /**
     * 统计数组中出现的次数
     */
    @Test
    public void testCountListMember(){
        List<String> asList = Arrays.asList("a", "b", "a", "b", "c", "d", "a");
        HashMultiset<String> hashMultiset = HashMultiset.create();
        hashMultiset.add("a",2);
        hashMultiset.addAll(asList);
        // 5
        System.out.println(hashMultiset.count("a"));
        // 1
        System.out.println(hashMultiset.count("c"));

    }
    /**
     * 统计数组中出现的次数
     */
    @Test
    public void testSetdiffcount(){
        Set<String> asList = Sets.newHashSet("a", "b", "a", "b", "c", "d", "a","t");
        Set<String> asList1 = Sets.newHashSet("g", "m", "a", "b", "c", "d", "a");
        //求交集
        Sets.SetView<String> strings = Sets.intersection(asList, asList1);
        //[a, b, c, d]
        System.out.println(strings);
        //求差集.
        Sets.SetView<String> difference = Sets.difference(asList1, asList);
        //TODO: 参数1 减去参数2  不是两个数组的不一致的数
        System.out.println(difference);

    }

    @Test
    public void testInts(){
        int[] ints  = new int[]{1,2,5,6,8,7};
        //false
        System.out.println(Ints.contains(ints,10));
        //1   TODO: 1大于  0 等于 -1 小于
        System.out.println(Ints.compare(11,10));
    }

    @Test
    public void testPartition(){
        List<Integer> asList = Arrays.asList(1, 2, 3, 5, 6, 67, 7, 8, 8, 9, 0, 0, 842, 123);
        List<List<Integer>> partition = Lists.partition(asList, 3);
        //result [[1, 2, 3], [5, 6, 67], [7, 8, 8], [9, 0, 0], [842, 123]]
        System.out.println(partition);

        //比如说需要分批次查询然后在汇总所有的数据
        List<String> list = partition.stream().map(lists ->
                lists.stream()
                        .map(integer -> integer+":tdo")
                        .collect(Collectors.toList()))
                .flatMap(strings -> strings.stream()).collect(Collectors.toList());
        // result [1:tdo, 2:tdo, 3:tdo, 5:tdo, 6:tdo, 67:tdo, 7:tdo, 8:tdo, 8:tdo, 9:tdo, 0:tdo, 0:tdo, 842:tdo, 123:tdo]
        System.out.println(list);
    }

    @Test
    public void testSetToMap(){
        //更多的应用场景为 对象转换为Map的时候 比如学生对象 以学生为key 学生Id为value

        Set<Student> hashSet = Sets.newHashSet();
        hashSet.add(Student.builder().name("张三").id(1).build());
        hashSet.add(Student.builder().name("张四").id(2).build());
        hashSet.add(Student.builder().name("张五").id(3).build());
        hashSet.add(Student.builder().name("张六").id(4).build());
        hashSet.add(Student.builder().name("张六").id(5).build());
        Map<Student, Integer> studentMap = Maps.asMap(hashSet, Student::getId);
        //result {Student(id=4, name=张六)=4, Student(id=3, name=张五)=3, Student(id=2, name=张四)=2, Student(id=1, name=张三)=1}
        System.out.println(studentMap);

    }

    @Test
    public  void testCopyOf(){
        List<String> objects = new ArrayList<>();
        objects.add("1");
        objects.add("2");
        objects.add("3");
        objects.add("9");
        objects.add("4");
        objects.add("5");
        //Guava copyOf
        ImmutableList<String> immutableList = ImmutableList.copyOf(objects);
        //copyOf  = [1, 2, 3, 9, 4, 5]
        System.out.println("copyOf  = " + immutableList.toString());
        // 在Guava copyOf 后进行裁剪
        List<String> copyOflistSubList = immutableList.subList(4, 6);
        //copyOf  listSubList = [4, 5]
        System.out.println("copyOf  listSubList = "+copyOflistSubList);
        //给原始数组增加元素   [1, 2, 3, 9, 4, 6, 5]
        objects.add(5,"6");
        //继续给在Guava copyOf 后进行裁剪
        List<String> copyOflistSubListAdd = immutableList.subList(4, 6);
        // copyOf  listSubListAdd = [4, 5] TODO: 和在给源数据增加数据前截取的内容一致
        System.out.println("copyOf  listSubListAdd = "+copyOflistSubListAdd);
        //copyOfAddOrigin  = [1, 2, 3, 9, 4, 5]
        System.out.println("copyOfAddOrigin  = " + immutableList.toString());

        //JAVA 进行copyOf
        List<String> list = Collections.unmodifiableList(objects);
        //JAVA copyOf 结果: JAVA = [1, 2, 3, 9, 4, 6, 5]
        System.out.println("JAVA = "+list);
        //在JAVA copyof的数组进行截图
        List<String> listSubList = list.subList(4, 6);
        //JAVA  listSubList = [4, 6]
        System.out.println("JAVA  listSubList = "+listSubList);
        //给源数据增加元素
        objects.add(5,"7");
        //继续在给上一步JAVA copyOf的数组上进行截取
        List<String> listSubListAdd = list.subList(4, 6);
        //JAVA  listSubListAdd = [4, 7]  TODO:截取到的元素发生变化
        System.out.println("JAVA  listSubListAdd = "+listSubListAdd);
        //JAVANotOrigin = [1, 2, 3, 9, 4, 7, 6, 5] TODO:随着对源数组的元素变化而变化.
        System.out.println("JAVANotOrigin = "+list);

    }

    @Test
    public void  testCopyOf2(){
        List<String> objects = new ArrayList<>();
        objects.add("1");
        objects.add("2");
        objects.add("3");
        objects.add("9");
        objects.add("4");
        objects.add("5");

        ImmutableList<String> list = ImmutableList.copyOf(objects);
        System.out.println("copyOf  = " + list.toString());
        // TODO: 添加失败
        /**
         * java.lang.UnsupportedOperationException
         * 	at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:246)
         * 	at chenyi.demo.groovyDemo.TestGroovy.testCopyOf2(TestGroovy.java:201)
         */
        list.add("af");
        System.out.println(list.toString());

    }
    @Test
    public void loadingCacheTest() throws ExecutionException {
        LoadingCache<String,String> loadingCache = CacheBuilder.newBuilder()
                .maximumSize(3)
                //10分钟后刷新缓存的数据
                .refreshAfterWrite(Duration.ofMillis(100))
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) throws Exception {
                        Thread.sleep(1000);
                        System.out.println(key + " load data");
                        return key + " add value";
                    }
                });
        System.out.println(loadingCache.get("a"));
        System.out.println(loadingCache.get("b"));
        System.out.println(loadingCache.get("a"));

    }

    /**
     * loadingCache
     *  适合单机缓存,原理和CurrentHashMap是一样的.但是在currentHashMap的基础上,有了更多的变化的
     *  maximumSize 设置最大缓存的长度
     *  concurrencyLevel 最大允许操作的并发线程
     *  recordStats 记录命中率
     *  softValues 使用软引用存储值。当内存不足并且该值其它强引用引用时,该缓存就会被回收
     *  weakKeys  使用弱引用存储键。当键没有其它(强或软)引用时,该缓存可能会被回收。
     *  weakValues  使用弱引用存储值。当值没有其它(强或软)引用时,该缓存可能会被回收。
     *  removalListener 当Key删除时,的监听事件
     *  expireAfterAccess 数据多长时间没有被访问,就过期
     *  expireAfterWrite  写入后多长时间,数据就过期了
     * @throws Exception
     */
    @Test
    public void testCache() throws Exception {
        LoadingCache<Integer, Student> loadingCache = CacheBuilder.newBuilder()
                //设置最大缓存的长度
                .maximumSize(20)
//                .expireAfterAccess(1000, TimeUnit.MINUTES)
                .expireAfterWrite(1000,TimeUnit.SECONDS)
                //最大允许操作的并发线程
                .concurrencyLevel(2)
                //记录命中率
                .recordStats()
                .softValues() //使用软引用存储值。当内存不足并且该值其它强引用引用时,该缓存就会被回收
                .weakKeys() //使用弱引用存储键。当键没有其它(强或软)引用时,该缓存可能会被回收。
                .weakValues() //使用弱引用存储值。当值没有其它(强或软)引用时,该缓存可能会被回收。
                //当Key删除时,的监听事件
                .removalListener(new RemovalListener<Object, Object>() {
                    @Override
                    public void onRemoval(RemovalNotification<Object, Object> notification) {
                        System.out.println( System.currentTimeMillis() +"   remove key " + notification.getKey() + " value " + notification.getValue());
                    }
                })
                //记录命中率
                .recordStats()
                .build(new CacheLoader<Integer, Student>() {
                    @Override
                    public Student load(Integer key) throws Exception {
                        System.out.println( System.currentTimeMillis() + "  load key " + key);
                        return Student.builder()
                                .id(key)
                                .name(System.currentTimeMillis() + "")
                                .build();
                    }
                });

        Student student = loadingCache.get(1);
        System.out.println(student);
        Thread.sleep(1000);
        Student student1 = loadingCache.get(1);
        System.out.println(student1);
//        Thread.sleep(15000);
        Student student2 = loadingCache.get(1);
        System.out.println(student2);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 20; i++) {
            final int h = i;
            executorService.execute(()->{
                try {
                    System.out.println(loadingCache.get(h));
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            });
        }

        Thread.sleep(1000);
        for (int i = 0; i < 20; i++) {
            final int h = i;
            executorService.execute(()->{
                try {
                    System.out.println(loadingCache.get(h));
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            });
        }
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println(loadingCache.stats().toString());
    }





}

参考链接:https://blog.csdn.net/pzjtian/article/details/106910046

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值