Preferred Idiom for Joining a Collection of Strings in Java

后端 未结 7 1599
悲哀的现实
悲哀的现实 2020-11-30 11:20

Given a Collection of Strings, how would you join them in plain Java, without using an external Library?

Given these variables:

Collection

        
相关标签:
7条回答
  • 2020-11-30 11:28

    May be instead of calling sb.length() again and again in a loop, i have slightly modified.

    StringBuilder sb = new StringBuilder();
    String separator = "";
    for(String item : data){
        sb.append(separator);
        separator=",";
        sb.append(item);
    }
    joined = sb.toString();
    
    0 讨论(0)
  • 2020-11-30 11:30

    In Java 8:

    String.join (separator, data)
    
    0 讨论(0)
  • 2020-11-30 11:32

    I'd say the best way of doing this (if by best you don't mean "most concise") without using Guava is using the technique Guava uses internally, which for your example would look something like this:

    Iterator<String> iter = data.iterator();
    StringBuilder sb = new StringBuilder();
    if (iter.hasNext()) {
      sb.append(iter.next());
      while (iter.hasNext()) {
        sb.append(separator).append(iter.next());
      }
    }
    String joined = sb.toString();
    

    This doesn't have to do a boolean check while iterating and doesn't have to do any postprocessing of the string.

    0 讨论(0)
  • 2020-11-30 11:32

    Java 8+

    joined =String.join(separator, data);

    Java 7 and below

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for(String item : data){
        if(!first || (first = false)) sb.append(separator);
        sb.append(item);
    }
    joined = sb.toString();
    
    0 讨论(0)
  • 2020-11-30 11:38

    Collectors can join Streams which is very useful if you want to filter or map your data.

    String joined = Stream.of("Snap", "Crackle", "Pop")
            .map(String::toUpperCase)
            .collect(Collectors.joining(", "));
    

    To get a Stream from a Collection, call stream() on it:

    Arrays.asList("Snap", "Crackle", "Pop").stream()
    
    0 讨论(0)
  • 2020-11-30 11:52

    Different intentions:

    For third-part tools, such as Guava's Joiner, which is not fast, but very flexible. There are many option methods to customize join behavior, such as skipNulls().

    Plain Java is fast, but it needs you write some lines of codes by yourself.

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