Guava字符串拼接工具类

Guava字符串拼接工具类

Joiner和Splitter 算是一个比较有意思的工具类了,可以实现字符串的分割和容器的拼接

具体的使用还是比较简单的,给个例子就可以清晰看到如何使用了

Joiner使用姿势

@Test
public void testJoiner() {
    List list = new ArrayList() {
        {
            add("12");
            add("@#");
            add("absc");
        }
    };

    String ans = Joiner.on(",").join(list);
    System.out.println("join: " + ans);

    String[] strs = new String[]{"123", "456", "789", "asdf"};
    ans = Joiner.on("&").join(strs);
    System.out.println(ans);


    Map params = new HashMap() {
        {
            put("key1", "123");
            put("key2", 678);
            put("key3", "what");
        }
    };

    ans = Joiner.on("&").withKeyValueSeparator("=").join(params);
    System.out.println("map->" + ans);
}

输出

join: 12,@#,absc
123&456&789&asdf
map->key1=123&key2=678&key3=what

Splitter使用姿势

@Test
public void testSplit() {
    String ans = "key1=123&key2=678&key3=what";

    Map map =Splitter.on("&").withKeyValueSeparator("=").split(ans);
    System.out.println("split map: " + map);


    ans = "123&456&789&asdf";
    List list = Splitter.on("&").splitToList(ans);
    System.out.println("split list: " + list);
}

输出

split map: {key1=123, key2=678, key3=what}
split list: [123, 456, 789, asdf]

参考

  • guava之Joiner 和 Splitter

你可能感兴趣的:(Guava字符串拼接工具类)