Preferred Idiom for Joining a Collection of Strings in Java

后端 未结 7 1641
悲哀的现实
悲哀的现实 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: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 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.

提交回复
热议问题