Guava:google公司开发的一款Java类库扩展工具包

时间:2023-02-01 12:17:09

Guava是google公司开发的一款Java类库扩展工具包

文档

maven 依赖

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>31.1-jre</version>
</dependency>

(目录)

示例1:连接字符串

package com.example;


import com.google.common.base.Joiner;

import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {

        // JDK 1.8
        String var1 = String.join("-", Arrays.asList("A", null, "C", "D"));
        System.out.println(var1);
        // A-null-C-D

        // guava
        Joiner joiner = Joiner.on("-").skipNulls();
        String var2 = joiner.join("A", null, "C", "D");
        System.out.println(var2);
        // A-C-D
    }
}

示例2:统计元素出现次数

package com.example;


import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {

        String[] words = {"A", "B", "C", "B"};

        // JDK 1.8
        Map<String, Integer> counts = new HashMap<String, Integer>();
        for (String word : words) {
            Integer count = counts.get(word);
            if (count == null) {
                counts.put(word, 1);
            } else {
                counts.put(word, count + 1);
            }
        }
        
        System.out.println(counts);
        // {A=1, B=2, C=1}

        // guava
        Multiset<String> multiset = HashMultiset.create();
        multiset.addAll(Arrays.asList(words));

        System.out.println(multiset);
        // [A, B x 2, C]
        System.out.println(multiset.count("B"));
        // 2
    }
}

示例3:key对应集合

package com.example;


import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Demo {
    public static void main(String[] args) {
        
        Multimap<String, Integer> multimap = ArrayListMultimap.create();
        multimap.put("A", 1);
        multimap.put("A", 2);
        multimap.put("B", 4);
        multimap.put("C", 5);

        System.out.println(multimap);
        // {A=[1, 2], B=[4], C=[5]}
    }
}

参考 Guava中这些Map的骚操作,让我的代码量减少了50% 一篇让你熟练掌握Google Guava包(全网最全)