Java: convert List to a String

前端 未结 22 2576
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve

Does Java have anything

相关标签:
22条回答
  • 2020-11-22 01:43

    With Java 8 you can do this without any third party library.

    If you want to join a Collection of Strings you can use the new String.join() method:

    List<String> list = Arrays.asList("foo", "bar", "baz");
    String joined = String.join(" and ", list); // "foo and bar and baz"
    

    If you have a Collection with another type than String you can use the Stream API with the joining Collector:

    List<Person> list = Arrays.asList(
      new Person("John", "Smith"),
      new Person("Anna", "Martinez"),
      new Person("Paul", "Watson ")
    );
    
    String joinedFirstNames = list.stream()
      .map(Person::getFirstName)
      .collect(Collectors.joining(", ")); // "John, Anna, Paul"
    

    The StringJoiner class may also be useful.

    0 讨论(0)
  • 2020-11-22 01:43

    No, there's no such convenience method in the standard Java API.

    Not surprisingly, Apache Commons provides such a thing in their StringUtils class in case you don't want to write it yourself.

    0 讨论(0)
  • 2020-11-22 01:43

    Code you have is right way to do it if you want to do using JDK without any external libraries. There is no simple "one-liner" that you could use in JDK.

    If you can use external libs, I recommend that you look into org.apache.commons.lang.StringUtils class in Apache Commons library.

    An example of usage:

    List<String> list = Arrays.asList("Bill", "Bob", "Steve");
    String joinedResult = StringUtils.join(list, " and ");
    
    0 讨论(0)
  • 2020-11-22 01:43

    EDIT

    I also notice the toString() underlying implementation issue, and about the element containing the separator but I thought I was being paranoid.

    Since I've got two comments on that regard, I'm changing my answer to:

    static String join( List<String> list , String replacement  ) {
        StringBuilder b = new StringBuilder();
        for( String item: list ) { 
            b.append( replacement ).append( item );
        }
        return b.toString().substring( replacement.length() );
    }
    

    Which looks pretty similar to the original question.

    So if you don't feel like adding the whole jar to your project you may use this.

    I think there's nothing wrong with your original code. Actually, the alternative that everyone's is suggesting looks almost the same ( although it does a number of additional validations )

    Here it is, along with the Apache 2.0 license.

    public static String join(Iterator iterator, String separator) {
        // handle null, zero and one elements before building a buffer
        if (iterator == null) {
            return null;
        }
        if (!iterator.hasNext()) {
            return EMPTY;
        }
        Object first = iterator.next();
        if (!iterator.hasNext()) {
            return ObjectUtils.toString(first);
        }
    
        // two or more elements
        StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
        if (first != null) {
            buf.append(first);
        }
    
        while (iterator.hasNext()) {
            if (separator != null) {
                buf.append(separator);
            }
            Object obj = iterator.next();
            if (obj != null) {
                buf.append(obj);
            }
        }
        return buf.toString();
    }
    

    Now we know, thank you open source

    0 讨论(0)
  • 2020-11-22 01:46

    An orthodox way to achieve it, is by defining a new function:

    public static String join(String joinStr, String... strings) {
        if (strings == null || strings.length == 0) {
            return "";
        } else if (strings.length == 1) {
            return strings[0];
        } else {
            StringBuilder sb = new StringBuilder(strings.length * 1 + strings[0].length());
            sb.append(strings[0]);
            for (int i = 1; i < strings.length; i++) {
                sb.append(joinStr).append(strings[i]);
            }
            return sb.toString();
        }
    }
    

    Sample:

    String[] array = new String[] { "7, 7, 7", "Bill", "Bob", "Steve",
            "[Bill]", "1,2,3", "Apple ][","~,~" };
    
    String joined;
    joined = join(" and ","7, 7, 7", "Bill", "Bob", "Steve", "[Bill]", "1,2,3", "Apple ][","~,~");
    joined = join(" and ", array); // same result
    
    System.out.println(joined);
    

    Output:

    7, 7, 7 and Bill and Bob and Steve and [Bill] and 1,2,3 and Apple ][ and ~,~

    0 讨论(0)
  • Java 8 does bring the

    Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
    

    method, that is nullsafe by using prefix + suffix for null values.

    It can be used in the following manner:

    String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))
    

    The Collectors.joining(CharSequence delimiter) method just calls joining(delimiter, "", "") internally.

    0 讨论(0)
提交回复
热议问题