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

前端 未结 30 2229
耶瑟儿~
耶瑟儿~ 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: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 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 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 list = ...;
    ListAdapter.adapt(list).makeString(",");
    
    
    

    Note: I am a committer for Eclipse collections.

    提交回复
    热议问题