String.join

8154 ワード

https://docs.oracle.com/javase/8/docs/api/ 
http://www.matools.com/api/java8
1シーンの使用 
Stringコレクションは、指定された区切り文字分割の文字列に急速に変換されます.最後の要素の後ろに区切り記号がありません.
1.1 java 8前 
@Test
public void test() {
    //   
    final String SEPARATOR = ",";
    List cities = Arrays.asList("Milan", "London", "New York", "San Francisco");
    StringBuilder csvBuilder = new StringBuilder();
    //          
    for (int i = 0; i < cities.size() - 1; i++) {
        csvBuilder.append(cities.get(i)).append(SEPARATOR);
    }
    //      
    csvBuilder.append(cities.get(cities.size() - 1));
    //Milan,London,New York,San Francisco
    System.out.println(csvBuilder.toString());
}
@Test
public void test() {
    //   
    final String SEPARATOR = ",";
    List cities = Arrays.asList("Milan", "London", "New York", "San Francisco");
    StringBuilder csvBuilder = new StringBuilder();
    for (String city : cities) {
        csvBuilder.append(city).append(SEPARATOR);
    }
    String csv = csvBuilder.toString();
    //Milan,London,New York,San Francisco,
    System.out.println(csv);
    //               
    csv = csv.substring(0, csv.length() - SEPARATOR.length());
    //Milan,London,New York,San Francisco
    System.out.println(csv);
}

1.2 java 8後
String.joinはコードを簡略化できます
@Test
public void test() {
    //   
    final String SEPARATOR = ",";
    List cities = Arrays.asList("Milan", "London", "New York", "San Francisco");
    String joinStr = String.join(SEPARATOR, cities);
    //Milan,London,New York,San Francisco
    System.out.println(joinStr);
}

Java 8のStream apiで前の効果を実現 
  • https://yuanyu.blog.csdn.net/article/details/105026457
  • @Test
    public void test() {
        //   
        final String SEPARATOR = ",";
        List cities = Arrays.asList("Milan", "London", "New York", "San Francisco");
        String joinStr = cities.stream().collect(Collectors.joining(SEPARATOR));
        //Milan,London,New York,San Francisco
        System.out.println(joinStr);
    }

    2公式文書
    https://docs.oracle.com/javase/8/docs/api/java/lang/String.html  static String join(CharSequence delimiter, CharSequence... elements) Returns a new String composed of copies of the  CharSequence elements  joined together with a copy of the specified  delimiter . static String join(CharSequence delimiter, Iterable extends CharSequence> elements) Returns a new  String  composed of copies of the  CharSequence elements  joined together with a copy of the specified  delimiter .
    //java.lang.String#join(java.lang.CharSequence, java.lang.CharSequence...)
    public static String join(CharSequence delimiter, CharSequence... elements) {
    
    //java.lang.String#join(java.lang.CharSequence, java.lang.Iterable extends java.lang.CharSequence>)
    public static String join(CharSequence delimiter,
    		Iterable extends CharSequence> elements) {

     
    @Test
    public void testJoin(){
        String message = String.join("-", "Java", "is", "cool");
        // message returned is: "Java-is-cool"
        System.out.println(message);
    }

     
    @Test
    public void testJoin() {
        List strings = new LinkedList<>();
        strings.add("Java");
        strings.add("is");
        strings.add("cool");
        String message = String.join(" ", strings);
        //message returned is: "Java is cool"
        System.out.println(message);
    
        String strMessage = strings.stream().collect(Collectors.joining(" "));
        //Java is cool
        System.out.println(strMessage);
    }
    @Test
    public void testJoin(){
        Set strings = new LinkedHashSet<>();
        strings.add("Java");
        strings.add("is");
        strings.add("very");
        strings.add("cool");
        String message = String.join("-", strings);
        //message returned is: "Java-is-very-cool"
        System.out.println(message);
    }

    3 CharSequenceインタフェース
    String.joinが入力したパラメータまたは反復器はCharSequenceインタフェースを実現する必要がある.現在入力されているパラメータがCharSequenceインタフェースを実装していないか、またはセットの反復器がCharSequenceインタフェースを実装していないプログラムは、エラーを報告します. Xxx cannot be cast to java.lang.CharSequence
    //java.lang.String#join(java.lang.CharSequence, java.lang.CharSequence...)
    public static String join(CharSequence delimiter, CharSequence... elements) {
    //java.lang.String#join(java.lang.CharSequence, java.lang.Iterable extends java.lang.CharSequence>)
    public static String join(CharSequence delimiter,
    		Iterable extends CharSequence> elements) {
    //public final class Integer extends Number implements Comparable {
    @Test
    public void test() {
        //   
        final String SEPARATOR = ",";
        List cities = Arrays.asList(1,2,3,4,5,6);
        //            
        //java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.lang.CharSequence
        String joinStr = String.join(SEPARATOR, (CharSequence) cities);
    }

    CharSequenceは文字列構造を記述するインタフェースで、このインタフェースには一般的に3つの一般的なサブクラスがあります.
    String.join_第1张图片
    // Stirng 
    public final class String
        implements java.io.Serializable, Comparable, CharSequence {
    
    // StringBuffer 
    public final class StringBuffer
       extends AbstractStringBuilder
       implements java.io.Serializable, CharSequence
    
    // StirngBuilder 
    public final class StringBuilder
        extends AbstractStringBuilder
        implements java.io.Serializable, CharSequence

    https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html
    Modifier and Type
    Method and Description char charAt(int index) Returns the  char  value at the specified index. default IntStream chars() Returns a stream of  int  zero-extending the  char  values from this sequence. default IntStream codePoints() Returns a stream of code point values from this sequence. int length() Returns the length of this character sequence. CharSequence subSequence(int start, int end) Returns a  CharSequence  that is a subsequence of this sequence. String toString() Returns a string containing the characters in this sequence in the same order as this sequence.
    package java.lang;
    public interface CharSequence {
        //
        int length();
        //
        char charAt(int index);
        //
        CharSequence subSequence(int start, int end);
        //
        public String toString();
        //
        public default IntStream chars() {...}
        public default IntStream codePoints() {...}
    }
    @Test
    public void test() {
        CharSequence str = "hello world";
        //11
        System.out.println(str.length());
        //h
        System.out.println(str.charAt(0));
        //world
        System.out.println(str.subSequence(6, 11));
        //hello world
        System.out.println(str.toString());
        //104 101 108 108 111 32 119 111 114 108 100 
        str.chars().forEach((item) -> {
            System.out.print(item + " ");
        });
        System.out.println();
        //104 101 108 108 111 32 119 111 114 108 100 
        str.codePoints().forEach((item) -> {
            System.out.print(item + " ");
        });
    }