guava字符串工具--------Joiner 根据给定的分隔符把字符串连接到一起

public class JoinerTest {

    public static void main(String args[]){

     //1、将list字符串集合,以,形式转为字符串
        List<String> list =new ArrayList<String>();
        list.add("xx");
        list.add("zz");
        list.add("dd");

        //Joiner.on(",")获得Joiner实例对象
        Joiner joiner =  Joiner.on(",");
        //joiner.join(list)传入操作的集合,并转成字符串格式
        System.out.println(joiner.join(list));
        //输出结果:xx,zz,dd

     //2、将Iterator<T>列表,转为字符串
        Iterator<String> it=list.iterator();
        String  str=Joiner.on("|").join(it);
        System.out.println(str);
        //输出结果:xx|zz|dd

     //3、连接多个字符串
        String str1=Joiner.on(",").join("小小","爸爸","妈妈","爷爷","奶奶");
        System.out.println(str1);
        //输出:小小,爸爸,妈妈,爷爷,奶奶

     //4、连接字符串与列表
        StringBuilder builder=new StringBuilder("小小最乖");
        //返回StringBuilder类型
        StringBuilder str2=Joiner.on(",").appendTo(builder,list);
        System.out.println(str2);
        //输出:小小最乖xx,zz,dd

     //5、跳过null值连接
        list.add(null);
        list.add("小小");
        //skipNulls()代表去除null
        String str3=Joiner.on(",").skipNulls().join(list);
        System.out.println(str3);
        //输出:xx,zz,dd,小小

     //6、替换null值进行连接
        String str4=Joiner.on(",").useForNull("空").join(list);
        System.out.println(str4);
        //输出:xx,zz,dd,空,小小

     //7、Map的键值对打印出来
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        Joiner.MapJoiner mapJoiner = Joiner.on(",").withKeyValueSeparator("=");
        System.out.println(mapJoiner.join(map));
        //输出:key1=value1,key2=value2,key3=value3     

    //8、一步将字符串转为List<Long>集合(前面先转为list<String>,后面用java8特性将List<String>转为List<Long>)
    List<Long> list=Splitter.on("#").splitToList("111#222#333").stream().mapToLong(str->Long.parseLong(str)).boxed().distinct().collect(Collectors.toList());
} }

















  

猜你喜欢

转载自www.cnblogs.com/jiaowoxiaofeng/p/11966661.html