Joiner使用Demo

工具类Joiner的用法

Joiner是Guava库下一个工具之一,提供了各种方法来处理字符串加入操作,对象等。
其主要的的用法有三种:

  • Joiner.on(“字符串连接符”);
  • withKeyValueSeparator方法返回一个MapJoiner对象
  • appendTo方法

具体功能是咋样子的,大家运行一下代码就知道结果了

import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Joiner;

public class TestJoiner {


    @Test
    public void testMapJoiner() {
        Map map = new HashMap();
        map.put("pter", "aaa");
        map.put("cuige", "bbb");
        map.put("han", "ccc");
//        Joiner.MapJoiner mapJoiner = Joiner.on("&").withKeyValueSeparator(":");
        //为了方便理解,将上面一句话拆成两句
        Joiner joiner = Joiner.on("&");
        Joiner.MapJoiner mapJoiner = joiner.withKeyValueSeparator("=");
        System.out.println(mapJoiner.join(map));
//输出:han=ccc&pter=aaa&cuige=bbb  在组装http参数的时候很有用
    }

    @Test
    public void testStringJoin() {
        Joiner joiner = Joiner.on("==");
        String str[] = {"aaa", "vbbb", "ccc", "ddd"};
        System.out.println(joiner.join(str));
    }
    //输出:aaa==vbbb==ccc==ddd
        @Test
    public void testAppendTo() {
        StringBuilder stringBuilder = new StringBuilder("peter_");
        ArrayList strs = new ArrayList<>();
        strs.add("nantian");
        strs.add("zhikang");
        strs.add("qunar");
        Joiner joiner = Joiner.on("_");
//        StringBuilder str1 = joiner.appendTo(stringBuilder,"aaa","bbb","ccc","ddd");
        StringBuilder str1 = joiner.appendTo(stringBuilder, strs);
        System.out.println(str1.toString());
//输出:peter_nantian_zhikang_qunar

    }


}

你可能感兴趣的:(Guava)