Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a direct equivalent in Java for Python's str.join? [duplicate]

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!

update a few years after...

Java 8 came to the rescue

like image 650
fortran Avatar asked Jul 13 '10 10:07

fortran


People also ask

What is StringUtils join in Java?

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.

Which method can be used to join STR in Python?

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.

How do you join characters in Java?

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.

How do you join elements in an array Java?

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 .


1 Answers

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)); } 
like image 191
BobTurbo Avatar answered Sep 22 '22 19:09

BobTurbo