Possible Duplicates:
What’s the best way to build a string of delimited items in Java?
Java: convert List<String> to a join()d string
In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the rest to get a comma separated string seems quite dull, is there something like str.join
in Python?
Extra clarification for avoiding it being closed as duplicate: I'd rather not use external libraries like Apache Commons.
Thanks!
Java 8 came to the rescue
Overview. join() is a static method of the StringUtils class that is used to join the elements of the provided array/iterable/iterator/varargs into a single string containing the provided list of elements.
Python String join() Method The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.
This method returns a String which is the result of join operation on the specified char values. For example: join(“-“, 1L, 2L, 3L) returns the string “1-2-3”. Parameters: This method accepts two mandatory parameters: separator: which is the character that occurs in between the joined char values.
To join elements of given string array strArray with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the string array strArray .
Nope there is not. Here is my attempt:
/** * Join a collection of strings and add commas as delimiters. * @require words.size() > 0 && words != null */ public static String concatWithCommas(Collection<String> words) { StringBuilder wordList = new StringBuilder(); for (String word : words) { wordList.append(word + ","); } return new String(wordList.deleteCharAt(wordList.length() - 1)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With