String#join

前回に引き続き、文字列の連結。

//String#joinメソッド。第一引数に区切り文字
//文字列連結
String joined = String.join(",", "a", "b", "c");
System.out.println(joined);
        
//String配列の要素の連結
String[] arr = {"aa", "bb", "cc"};
String arrJoined = String.join(":", arr);
System.out.println(arrJoined);
        
//List<String> の要素の連結
List<String> list = Arrays.asList("aaa", "bbb", "ccc");
String listJoined = String.join("*", list);
System.out.println(listJoined);

//Streamを使用した場合
List<String> list2 = Arrays.asList("XX", "YY", "ZZ");
String listJoined2 = list2.stream().collect(Collectors.joining("|"));
System.out.println(listJoined2);

結果

a,b,c
aa:bb:cc
aaa*bbb*ccc
XX|YY|ZZ