What's the best way to build a string of delimited items in Java?

前端 未结 30 2123
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i

相关标签:
30条回答
  • 2020-11-22 06:23

    in Java 8 you can do this like:

    list.stream().map(Object::toString)
            .collect(Collectors.joining(delimiter));
    

    if list has nulls you can use:

    list.stream().map(String::valueOf)
            .collect(Collectors.joining(delimiter))
    

    it also supports prefix and suffix:

    list.stream().map(String::valueOf)
            .collect(Collectors.joining(delimiter, prefix, suffix));
    
    0 讨论(0)
  • 2020-11-22 06:23

    For those who are in a Spring context their StringUtils class is useful as well:

    There are many useful shortcuts like:

    • collectionToCommaDelimitedString(Collection coll)
    • collectionToDelimitedString(Collection coll, String delim)
    • arrayToDelimitedString(Object[] arr, String delim)

    and many others.

    This can be helpful if you are not already using Java 8 and you are already in a Spring context.

    I prefer it against the Apache Commons (although very good as well) for the Collection support which is easier like this:

    // Encoding Set<String> to String delimited 
    String asString = org.springframework.util.StringUtils.collectionToDelimitedString(codes, ";");
    
    // Decoding String delimited to Set
    Set<String> collection = org.springframework.util.StringUtils.commaDelimitedListToSet(asString);
    
    0 讨论(0)
  • 2020-11-22 06:24

    If you are using Spring MVC then you can try following steps.

    import org.springframework.util.StringUtils;
    
    List<String> groupIds = new List<String>;   
    groupIds.add("a");    
    groupIds.add("b");    
    groupIds.add("c");
    
    String csv = StringUtils.arrayToCommaDelimitedString(groupIds.toArray());
    

    It will result to a,b,c

    0 讨论(0)
  • 2020-11-22 06:24

    If you're using Eclipse Collections, you can use makeString() or appendString().

    makeString() returns a String representation, similar to toString().

    It has three forms

    • makeString(start, separator, end)
    • makeString(separator) defaults start and end to empty strings
    • makeString() defaults the separator to ", " (comma and space)

    Code example:

    MutableList<Integer> list = FastList.newListWith(1, 2, 3);
    assertEquals("[1/2/3]", list.makeString("[", "/", "]"));
    assertEquals("1/2/3", list.makeString("/"));
    assertEquals("1, 2, 3", list.makeString());
    assertEquals(list.toString(), list.makeString("[", ", ", "]"));
    

    appendString() is similar to makeString(), but it appends to an Appendable (like StringBuilder) and is void. It has the same three forms, with an additional first argument, the Appendable.

    MutableList<Integer> list = FastList.newListWith(1, 2, 3);
    Appendable appendable = new StringBuilder();
    list.appendString(appendable, "[", "/", "]");
    assertEquals("[1/2/3]", appendable.toString());
    

    If you can't convert your collection to an Eclipse Collections type, just adapt it with the relevant adapter.

    List<Object> list = ...;
    ListAdapter.adapt(list).makeString(",");
    

    Note: I am a committer for Eclipse collections.

    0 讨论(0)
  • 2020-11-22 06:24

    You can try something like this:

    StringBuilder sb = new StringBuilder();
    if (condition) { sb.append("elementName").append(","); }
    if (anotherCondition) { sb.append("anotherElementName").append(","); }
    String parameterString = sb.toString();
    
    0 讨论(0)
  • 2020-11-22 06:26

    Pre Java 8:

    Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby:

    StringUtils.join(java.lang.Iterable,char)


    Java 8:

    Java 8 provides joining out of the box via StringJoiner and String.join(). The snippets below show how you can use them:

    StringJoiner

    StringJoiner joiner = new StringJoiner(",");
    joiner.add("01").add("02").add("03");
    String joinedString = joiner.toString(); // "01,02,03"
    

    String.join(CharSequence delimiter, CharSequence... elements))

    String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"
    

    String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

    List<String> strings = new LinkedList<>();
    strings.add("Java");strings.add("is");
    strings.add("cool");
    String message = String.join(" ", strings);
    //message returned is: "Java is cool"
    
    0 讨论(0)
提交回复
热议问题