Java: convert List to a String

前端 未结 22 2607
日久生厌
日久生厌 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:49

    Google's Guava API also has .join(), although (as should be obvious with the other replies), Apache Commons is pretty much the standard here.

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

    Three possibilities in Java 8:

    List<String> list = Arrays.asList("Alice", "Bob", "Charlie")
    
    String result = String.join(" and ", list);
    
    result = list.stream().collect(Collectors.joining(" and "));
    
    result = list.stream().reduce((t, u) -> t + " and " + u).orElse("");
    
    0 讨论(0)
  • 2020-11-22 01:51

    Not out of the box, but many libraries have similar:

    Commons Lang:

    org.apache.commons.lang.StringUtils.join(list, conjunction);
    

    Spring:

    org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);
    
    0 讨论(0)
  • 2020-11-22 01:51

    With a java 8 collector, this can be done with the following code:

    Arrays.asList("Bill", "Bob", "Steve").stream()
    .collect(Collectors.joining(" and "));
    

    Also, the simplest solution in java 8:

    String.join(" and ", "Bill", "Bob", "Steve");
    

    or

    String.join(" and ", Arrays.asList("Bill", "Bob", "Steve"));
    
    0 讨论(0)
  • 2020-11-22 01:54

    On Android you could use TextUtils class.

    TextUtils.join(" and ", names);
    
    0 讨论(0)
  • 2020-11-22 01:54

    Java 8 solution with java.util.StringJoiner

    Java 8 has got a StringJoiner class. But you still need to write a bit of boilerplate, because it's Java.

    StringJoiner sj = new StringJoiner(" and ", "" , "");
    String[] names = {"Bill", "Bob", "Steve"};
    for (String name : names) {
       sj.add(name);
    }
    System.out.println(sj);
    
    0 讨论(0)
提交回复
热议问题