Guava入门

其实我用guava差不多大半年时间了,发现guava真的特别好用,又会使代码变得很简洁,最近又系统的学习了一下,大致讲一下😊

什么是guava呢?

guava就是类库,是java api的增强与扩展,里面有大量的方法供我们使用,使用之前需要引入包

<dependencies>
        <!--guava依赖-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.0.1</version>
        </dependency>
</dependencies>

guava有哪些方法呢?我们先从以下几方面开始学习:

  1. 字符串处理:分割,连接,填充
  2. 新增的集合类型
  3. 原生类型

1.字符串的处理:分割,连接,填充

   a. joiner 连接器

joiner on就是将list用,连接转成字符串

@Test
    public void joinerListTest() {
        List<String> lists = Lists.newArrayList("a","b","g","8","9");
        String result = Joiner.on(",").join(lists);
        System.out.println(result);
    }

结果:a,b,g,8,9

joiner skipNulls()连接跳过null元素(第一个test为了跟第二个进行比对一下)

@Test
    public void joinerListTest1() {
        List<String> lists = Lists.newArrayList("a","b","g",null,"8","9");
        String result = Joiner.on(",").join(lists);
        System.out.println(result);
    }

结果:a,b,g,null,8,9

@Test
public void joinerListTest2() {
    List<String> lists = Lists.newArrayList("a","b,"g",null,"8","9");
    String result = Joiner.on(",").skipNulls().join(lists);
    System.out.println(result);
}
结果:a,b,g,8,9

  如果连接的时候list里面含有null值,会报空指针,因为join实现如下:

1.
public final String join(Iterable<?> parts) {
        return this.join(parts.iterator());
    }

2.
public final String join(Iterator<?> parts) {
        return this.appendTo(new StringBuilder(), parts).toString();
    }

3.
@CanIgnoreReturnValue
    public final StringBuilder appendTo(StringBuilder builder, Iterator<?> parts) {
        try {
            this.appendTo((Appendable)builder, (Iterator)parts);
            return builder;
        } catch (IOException var4) {
            throw new AssertionError(var4);
        }
    }

4.
@CanIgnoreReturnValue
    public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
        Preconditions.checkNotNull(appendable);
        if (parts.hasNext()) {
            appendable.append(this.toString(parts.next()));

            while(parts.hasNext()) {
                appendable.append(this.separator);
                appendable.append(this.toString(parts.next()));
            }
        }
        return appendable;
    }

5.
@CanIgnoreReturnValue
    public static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw new NullPointerException();
        } else {
            return reference;
        }
    }

 joiner useForNull(final String value)用value替换null元素值

@Test
    public void useNullListTest() {
        List<String> lists = Lists.newArrayList("a", "b", "g", null, "8", "9");
        String result = Joiner.on(",").useForNull("哈哈").join(lists);
        System.out.println(result);
    }

结果:a,b,g,哈哈,8,9

 joiner withKeyValueSeparator(String value)   map连接器,keyValueSeparator为key和value之间的分隔符

@Test
    public void withMapTest() {
        Map<Integer, String> maps = Maps.newHashMap();
        maps.put(1, "哈哈");
        maps.put(2, "压压");
        String result = Joiner.on(",").withKeyValueSeparator(":").join(maps);
        System.out.println(result);
        System.out.println(maps);
    }

结果:
1:哈哈,2:压压
{1=哈哈, 2=压压}

  b. splitter 拆分器

 splitter on 拆分

@Test
    public void splitterListTest() {
        String test = "34344,34,34,哈哈";
        List<String> lists = Splitter.on(",").splitToList(test);
        System.out.println(lists);
    }

结果:[34344, 34, 34, 哈哈]

 splitter trimResults 拆分去除前后空格

@Test
    public void trimResultListTest() {
        String test = "  34344,34,34,哈哈 ";
        List<String> lists = Splitter.on(",").trimResults().splitToList(test);
        System.out.println(lists);
    }

结果:[34344, 34, 34, 哈哈]

splitter omitEmptyStrings 去除拆分出来空的字符串

@Test
    public void omitEmptyStringsTest() {
        String test = "  3434,434,34,,哈哈 ";
        List<String> lists = Splitter.on(",").omitEmptyStrings().splitToList(test);
        System.out.println(lists);
    }

结果:[  3434, 434, 34, 哈哈 ]

splitter fixedLength(int lenght) 把字符串按固定长度分割

@Test
    public void fixedLengthTest() {
        String test = "343443434哈哈";
        List<String> lists = Splitter.fixedLength(3).splitToList(test);
        System.out.println(lists);
    }

结果:[343, 443, 434, 哈哈]

  b. charMatcher 匹配器

charMatcher is(Char char)  给单一字符匹配

@Test
    public void isTest() {
        String str = "12312,agg";
        CharMatcher charMatcher1 = CharMatcher.is('g');
        System.out.println(charMatcher1.retainFrom(str));
    }

结果:gg

charMatcher  retainFrom(String s)  在字符序列中保留匹配字符,移除其他字符

@Test
    public void charMatcherTest() {
        String str = "12312,agg  ";
        //两个匹配符,先匹配再操作
        CharMatcher charMatcher1 = CharMatcher.is('1');
        CharMatcher charMatcher2 = CharMatcher.is('2');
        //两个CharMatcher或操作
        CharMatcher charMatcher3 = charMatcher1.or(charMatcher2);
        System.out.println(charMatcher3.retainFrom(str));
    }

结果:1212

charMatcher matchersAllOf(Char char) 测试是否字符序列所有字符都匹配

@Test
    public void matchesAllOfTest() {
        String str = "12312,agg";
        CharMatcher charMatcher1 = CharMatcher.is('g');
        System.out.println(charMatcher1.matchesAllOf(str));
    }

结果:false
@Test
    public void matchesAllOfTest() {
        String str = "ggggg";
        CharMatcher charMatcher1 = CharMatcher.is('g');
        System.out.println(charMatcher1.matchesAllOf(str));
    }

结果:true

2.原生类型

 定义list,map

@Test
    public void test() {
        //JDK 
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        //guava
        List<String> lists = Lists.newArrayList("a", "b", "g", null, "8", "9");
        List<String> lists1 = Lists.newArrayList();
        Map<Integer, String> maps = Maps.newHashMap();
}

 

3.新增集合(这里我只讲一下Mulitmap,平时用这个会使代码很方便,这里我就多讲一下)

   Multimap就是将相同key的value值放在一个list里面,这样子取相同key下面的所有value值就非常简单了,不然还得for循环去匹配,把相同key值的value值找出来,在进行处理。map<key,value>键值key不能重复,所以当遇到这样子场景的时候map就非常不适合了,下面我们看下例子:

  @Test
    public void test1(){
        //假设a表跟b表是一对多的关系,通过a表id是b表的外键,比如从b表查出了一堆数据,想把a.id相同的数据放在一起,A,B分别代表a,b表的model
        List<B> bList = BMapper.selectByExample(XXXXX);
        Multimap<Integer,B> bMultimap = ArrayListMultimap.create();
        bList.forEach(v->{
            bMultimap.put(v.getAId(),v);   
        });

    }

 Multimap.get(key)即使没有key值,会返回空的list。

 Multimap.keySet()返回的用set<T>表示的不重复key;Multimap.keys()返回的是用Multiset表示的key,key数量跟value值数量一致;Multimap.containKeys()是表示是否包含这个key;

 Multimap.size()返回所有值的个数,而非不同键的个数。要得到不同键的个数,要用Multimap.keySet().size()

 

posted @ 2019-07-09 20:03  王小鑫  阅读(25369)  评论(0编辑  收藏  举报