0
点赞
收藏
分享

微信扫一扫

字符串拼接 #yyds干货盘点#

简介

StringJoiner是java8新增的工具类,StringJoiner是依赖StringBuilder实现,性能和StringBuilder差不多,也是非线程安全的。

示例

public static void main(String[] args) {
    String res1 = String.join("-", "2020","11","11");
    System.out.println(res1); //2020-11-11

    String res2 = String.join("*", List.of("aa","bb","cc"));
    System.out.println(res2);//aa*bb*cc

    List<String> list1= List.of("11","22","33","44");
        String res3 = list1.stream()
        .map(item->item)
        .collect(Collectors.joining("-"));
    System.out.println(res3);//11-22-33-44

    List<Dept> list2 = List.of(new Dept(10,"ACCOUNTING","NEWYORK"),
          new Dept(20,"RESEARCH","DALLAS"),
          new Dept(30,"SALES","CHICAGO"));
    String res4 = list2.stream().map(item->item.getDname())
    .collect(Collectors.joining(", ","{","}"));
    System.out.println(res4); //{ACCOUNTING, RESEARCH, SALES}

    StringJoiner sj1 = new StringJoiner(",");
    sj1.add("zhangsan");
    sj1.add("lisi");
    sj1.add("wanger");
    System.out.println(sj1);// zhangsan,lisi,wanger

    StringJoiner sj2 = new StringJoiner("/","C:/","/abc.txt").add("aa")
        .add("bb")
        .add("cc");
    System.out.println(sj2); //C:/aa/bb/cc/abc.txt
}

结果:
image.png

举报

相关推荐

0 条评论