欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Guava 常用方法

程序员文章站 2022-06-15 16:03:14
...

转载:https://dalin.blog.csdn.net/article/details/109396692

1. 数据校验

/**
     * 数据校验
     */
    @Test
    public void jiaoyan() {
        String param = "who are you";
        String name = Preconditions.checkNotNull(param);
        System.out.println(name);

        String param2 = null;
        String name2 = Preconditions.checkNotNull(param2, "param2 is null");
        System.out.println(name2);
    }

结果:

who are you

java.lang.NullPointerException: param2 is null
...

2. 是否越界

 // Guava 中快速创建ArrayList
        List<String> list = Lists.newArrayList("A", "B", "C", "D");
        // 开始校验
        int index = Preconditions.checkElementIndex(5, list.size());

结果:

java.lang.IndexOutOfBoundsException: index (5) must be less than size (4)
...

3. 集合

3.1 不可变集合

@Test
    public void buKeBianCollection() {
        // 创建方式1:of
        ImmutableSet<String> immutableSet = ImmutableSet.of("a", "b", "c");
        immutableSet.forEach(System.out::println);

        // 创建方式2:builder
        ImmutableSet<String> immutableSet2 = ImmutableSet.<String>builder()
                .add("hello")
                .add("汤姆")
                .build();
        immutableSet2.forEach(System.out::println);

        // 创建方式3:从其他集合中拷贝创建
        ArrayList<String> arrayList = new ArrayList();
        arrayList.add("ccc");
        arrayList.add("xxx");
        ImmutableSet<String> immutableSet3 = ImmutableSet.copyOf(arrayList);
        immutableSet3.forEach(System.out::println);

        // 使用 JDK Collections 创建不可变 List
        List<String> list = Collections.unmodifiableList(arrayList);
        list.forEach(System.out::println);
        //list.add("vvv"); // java.lang.UnsupportedOperationException
    }

注意:

  • 使用 Guava 创建的不可变集合是拒绝 null 值的,因为在 Google 内部调查中,95% 的情况下都不需要放入 null 值。
  • 使用 JDK 提供的不可变集合创建成功后,原集合添加元素会体现在不可变集合中,而 Guava 的不可变集合不会有这个问题。
        List<String> arrayList2 = new ArrayList<>();
        arrayList2.add("l");
        arrayList2.add("iu");
        List<String> jdkList = Collections.unmodifiableList(arrayList2);
        ImmutableList<String> immutableList = ImmutableList.copyOf(arrayList2);
        arrayList2.add("shuai");
        jdkList.forEach(System.out::println);// result: a b ccc
        System.out.println("-------");
        immutableList.forEach(System.out::println);// result: a b

3.2 集合创建工厂

@Test
    public void createCollections() {
        List<String> list1 = Lists.newArrayList();

        List<String> list2 = Lists.newArrayList("a", "b", "c");

        HashMap<Object, Object> hashMap = Maps.newHashMap();
        ConcurrentMap<Object, Object> concurrentMap = Maps.newConcurrentMap();
        TreeMap<Comparable, Object> treeMap = Maps.newTreeMap();

        HashSet<Object> hashSet = Sets.newHashSet();
        HashSet<String> newHashSet = Sets.newHashSet("a", "a", "b", "c");
    }

3.3 交集、并集、差集

	@Test
    public void compileCollections() {
        Set<String> newHashSet1 = Sets.newHashSet("a", "a", "b", "c");
        Set<String> newHashSet2 = Sets.newHashSet("b", "b", "c", "d");

        // 交集
        Sets.SetView<String> intersection = Sets.intersection(newHashSet1, newHashSet2);
        System.out.println(intersection); // [b, c]

        // 并集
        Sets.SetView<String> unionSet = Sets.union(newHashSet1, newHashSet2);
        System.out.println(unionSet); // [a, b, c, d]

        // newHashSet1 中存在,newHashSet2 中不存在
        Sets.SetView<String> setView = Sets.difference(newHashSet1, newHashSet2);
        System.out.println(setView); // [a]
    }

3.4 集合统计

1. 集合统计(计数): 统计相同元素出现的次数

@Test
    public void countCollections() {
        
        // use JDK
        List<String> words = Lists.newArrayList("a", "b", "c", "a", "e");

        Map<String, Integer> countMap = Maps.newHashMap();
        for (String word : words) {
            Integer count = countMap.get(word);
            count = (count == null) ? 1 : ++count;
            countMap.put(word, count);
        }

        countMap.forEach((k, v) -> System.out.println(k + " : " + v));

        // use Guava
        ArrayList<String> arrayList = Lists.newArrayList("a", "b", "c", "d", "a", "c");
        HashMultiset<String> multiset = HashMultiset.create(arrayList);
        multiset.elementSet().forEach(s -> System.out.println(s + ":" + multiset.count(s)));
    }

结果:

a : 2
b : 1
c : 1
e : 1
a:2
b:1
c:2
d:1

2. 集合统计(分类): 把很多动物按照种类进行分类

	@Test
    public void countCollectionsMore() {
        // JDK 原生写法
        HashMap<String, Set<String>> animalMap = new HashMap<>();
        HashSet<String> dogSet = new HashSet<>();
        dogSet.add("旺财");
        dogSet.add("大黄");
        animalMap.put("狗", dogSet);
        HashSet<String> catSet = new HashSet<>();
        catSet.add("加菲");
        catSet.add("汤姆");
        animalMap.put("猫", catSet);
        System.out.println(animalMap.get("猫")); // [加菲, 汤姆]

        // use guava
        // HashMultimap 可以扔进去重复的 key 值,最后获取时可以得到所有的 value 值
        HashMultimap<String, String> multimap = HashMultimap.create();
        multimap.put("狗", "大黄");
        multimap.put("狗", "旺财");
        multimap.put("猫", "加菲");
        multimap.put("猫", "汤姆");
        System.out.println(multimap.get("猫")); // [加菲, 汤姆]
    }

4. 字符串

4.1 字符拼接

	@Test
    public void StrJoin(){

        // JDK 方式一
        ArrayList<String> list = Lists.newArrayList("a", "b", "c", null);
        String join = String.join(",", list);
        System.out.println(join);

        // JDK 方式二
        String result = list.stream().collect(Collectors.joining(","));
        System.out.println(result);

        // JDK 方式三
        StringJoiner joiner = new StringJoiner(",");
        list.forEach(joiner::add);
        System.out.println(joiner.toString());

        // use guava
        ArrayList<String> list2 = Lists.newArrayList("a","b","c",null);
        String join1 = Joiner.on(",").skipNulls().join(list2);
        System.out.println(join1);

        String join2 = Joiner.on(",").useForNull("空空如也").join("jack","lucy","Lili",null);
        System.out.println(join2);

    }

4.2 字符分隔

 	@Test
    public void StrSplit(){
        // use JDK
        String str = ",a,,b,";
        String[] splitArr = str.split(",");
        Arrays.stream(splitArr).forEach(System.out::println);

        // use guava
        Iterable<String> split = Splitter.on(",")
                .omitEmptyStrings() // 忽略空值
                .trimResults() // 过滤结果中的空白
                .split(str);
        split.forEach(System.out::println);
    }

5. 临时缓存

package cn.luis.guava;

import com.google.common.cache.*;
import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class GuavaCacheDemo {

    @Test
    public void test() throws ExecutionException, InterruptedException {
        CacheLoader cacheLoader = new CacheLoader<String, Animal>() {
            @Override
            public Animal load(String s) throws Exception {
                return new Animal();
            }
        };

        /*
          容量、过期时间、失效监听器
         */
        LoadingCache<String, Animal> loadingCache = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(3, TimeUnit.SECONDS)
                .removalListener(new MyRemovalListener())
                .build(cacheLoader);
        loadingCache.put("狗", new Animal("旺财", 1));
        loadingCache.put("猫", new Animal("汤姆", 3));
        loadingCache.put("狼", new Animal("灰太狼", 4));
        loadingCache.invalidate("猫"); // 手动失效

        Animal animal = loadingCache.get("狼");
        System.out.println(animal);
        Thread.sleep(4 * 1000);
        // 狼已经自动过去,获取为 null 值报错
        System.out.println(loadingCache.get("狼"));

    }


    /**
     * 缓存移除监听器
     */
    class MyRemovalListener implements RemovalListener<String, Animal> {

        @Override
        public void onRemoval(RemovalNotification<String, Animal> notification) {
            String reason = String.format("key=%s,value=%s,reason=%s", notification.getKey(), notification.getValue(), notification.getCause());
            System.out.println(reason);
        }


    }
}

package cn.luis.guava;

public class Animal {

    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Animal(){}

    public Animal(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

相关标签: 技术栈