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

前端 未结 30 2184
耶瑟儿~
耶瑟儿~ 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:18

    Why not write your own join() method? It would take as parameters collection of Strings and a delimiter String. Within the method iterate over the collection and build up your result in a StringBuffer.

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

    You could write a little join-style utility method that works on java.util.Lists

    public static String join(List<String> list, String delim) {
    
        StringBuilder sb = new StringBuilder();
    
        String loopDelim = "";
    
        for(String s : list) {
    
            sb.append(loopDelim);
            sb.append(s);            
    
            loopDelim = delim;
        }
    
        return sb.toString();
    }
    

    Then use it like so:

        List<String> list = new ArrayList<String>();
    
        if( condition )        list.add("elementName");
        if( anotherCondition ) list.add("anotherElementName");
    
        join(list, ",");
    
    0 讨论(0)
  • 2020-11-22 06:20

    Java 8 Native Type

    List<Integer> example;
    example.add(1);
    example.add(2);
    example.add(3);
    ...
    example.stream().collect(Collectors.joining(","));
    

    Java 8 Custom Object:

    List<Person> person;
    ...
    person.stream().map(Person::getAge).collect(Collectors.joining(","));
    
    0 讨论(0)
  • 2020-11-22 06:20

    You should probably use a StringBuilder with the append method to construct your result, but otherwise this is as good of a solution as Java has to offer.

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

    Don't know if this really is any better, but at least it's using StringBuilder, which may be slightly more efficient.

    Down below is a more generic approach if you can build up the list of parameters BEFORE doing any parameter delimiting.

    // Answers real question
    public String appendWithDelimiters(String delimiter, String original, String addition) {
        StringBuilder sb = new StringBuilder(original);
        if(sb.length()!=0) {
            sb.append(delimiter).append(addition);
        } else {
            sb.append(addition);
        }
        return sb.toString();
    }
    
    
    // A more generic case.
    // ... means a list of indeterminate length of Strings.
    public String appendWithDelimitersGeneric(String delimiter, String... strings) {
        StringBuilder sb = new StringBuilder();
        for (String string : strings) {
            if(sb.length()!=0) {
                sb.append(delimiter).append(string);
            } else {
                sb.append(string);
            }
        }
    
        return sb.toString();
    }
    
    public void testAppendWithDelimiters() {
        String string = appendWithDelimitersGeneric(",", "string1", "string2", "string3");
    }
    
    0 讨论(0)
  • 2020-11-22 06:21

    So a couple of things you might do to get the feel that it seems like you're looking for:

    1) Extend List class - and add the join method to it. The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method)

    2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class: so you could write that join method and add it as an extension method to List or even to Collection.

    Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet :) But it should work just fine.

    To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.

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