[Java]用于将链表变成字符串并在元素之间插入分隔符的有用函数“String.join”

将链表变成字符串并在元素之间插入分隔符,这种动作最常见于组合sql文“select a,b,c from tb”这种场景scenario,其中a,b,c你是存贮在链表中的,

如果要加逗号要么在循环中识别是否最后一个,要么拼装好后删掉最后一个多余的逗号,无论哪种方法都让代码显得不是那么靓仔。

JavaScript为此提供了一种jion方法,JDK8里java也采用了这个很方便的函数,示例如下:

        List<String> ls=new ArrayList<String>();
        ls.add("Andy");
        String str=String.join(",", ls);
        System.out.println("str="+str);// 当只有一个元素时,join方法不会乱加分隔符
        
        ls.add("Bill");
        ls.add("Cindy");
        str=String.join(",", ls);
        System.out.println("str="+str);// 当只有多个元素时,join方法会把分隔符放在中间

输出如下:

str=Andy
str=Andy,Bill,Cindy

String.join ! Enjoy it!

--END-- 2019年9月6日10点29分

原文地址:https://www.cnblogs.com/heyang78/p/11471413.html