Using Java 8 you can do this in a very clean way:
String.join(delimiter, elements);
This works in three ways:
1) directly specifying the elements
String joined1 = String.join(",", "a", "b", "c");
2) using arrays
String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);
3) using iterables
List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);
Answer from skiwi on Stack OverflowUsing Java 8 you can do this in a very clean way:
String.join(delimiter, elements);
This works in three ways:
1) directly specifying the elements
String joined1 = String.join(",", "a", "b", "c");
2) using arrays
String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);
3) using iterables
List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);
If you're on Android you can TextUtils.join(delimiter, tokens)
Before I review your code I want to point out that Java has a String.join() method which does exactly that. Now to your code:
You use StringBuilder, good. You take care of not appending a seperator after the last and not prepending before the first element, also good. You don't handle null values though, it's your decision if you want to handle them separately or just let Java just throw a NPE. For the separator however, a null appends literally null to the String, I'd rather default to "" if separator is null. A way to get rid of the flag:
public String getArrayAsString(String[] stringArray, String separator) {
if(stringArray == null || stringArray.length == 0) return "";
With this we already ensured that our stringArray has at least one entry. What we can do now is initialize the StringBuilder with the first String:
StringBuilder finalString = new StringBuilder(stringArray[0]);
Since all strings after the first one need to prepend the separator, we don't need the flag anymore. Unfortunately, we can't use a foreach loop, since we have to start at index 1 as the element at index 0 is already in the StringBuilder:
for(int i = 1; i < stringArray.length; ++i)
finalString.append(separator).append(stringArray[i]);
And then just return what we got:
return finalString.toString();
Whole function:
public String getArrayAsString(String[] stringArray, String separator) {
if(stringArray == null || stringArray.length == 0) return "";
StringBuilder finalString = new StringBuilder(stringArray[0]);
for(int i = 1; i < stringArray.length; ++i)
finalString.append(separator).append(stringArray[i]);
return finalString.toString();
}
Edit:
In String.join() the parameters are swapped, so the separator comes first, the array second:
String[] arr = new String[]{"Hello", "World"};
System.out.println(String.join(" | ", arr));
System.out.println(getArrayAsString(arr, " | ")); //Your function
Output:
Hello | World
Hello | World
Working code at ideone.com
I would probably drop an enchanced loop, and stick to indices:
finalString.append(stringArray[0]);
for (int i = 1; i < stringArray.size(); ++i) {
finalString.append(separator);
finalString.append(s);
}
You may try to keep the enchanced loop by wrapping the array into a List, get a List.sublist(1)and iterate over it. However I am not sure it is more concise/elegant.
Java 8+
Use String.join():
String str = String.join(",", arr);
Note that arr can also be any Iterable (such as a list), not just an array.
If you have a Stream, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.
Android
Use TextUtils.join():
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:
String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);
Produces:
a-b-1
Either write a simple method yourself, or use one of the various utilities out there.
Personally I use apache StringUtils (StringUtils.join)
edit: in Java 8, you don't need this at all anymore:
String joined = String.join(",", name);
Android developers are probably looking for TextUtils.join
Android docs: http://developer.android.com/reference/android/text/TextUtils.html
Code:
String[] name = {"amit", "rahul", "surya"};
TextUtils.join(",",name)
Here's what I came up with. There are several ways to do this and they depend on the tools you are using.
Using StringUtils and ArrayUtils from Commons Lang:
Use with AIint[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = StringUtils.join(ArrayUtils.toObject(arr), " - ");
You can't just use StringUtils.join(arr, " - "); because StringUtils doesn't have that overloaded version of method. Though, it has method StringUtils.join(int[], char).
Works at any Java version, from 1.2.
Using Java 8 streams:
Something like this:
Use with AIint[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" - "));
In fact, there are lot of variations to achieve it using streams.
Java 8's method String.join() works only with strings, so to use it you still have to convert int[] to String[].
Use with AIString[] sarr = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new);
String result = String.join(" - ", sarr);
If you're stuck using Java 7 or earlier with no libraries, you could write your own utility method:
Use with AIpublic static String myJoin(int[] arr, String separator) {
if (null == arr || 0 == arr.length) return "";
StringBuilder sb = new StringBuilder(256);
sb.append(arr[0]);
//if (arr.length == 1) return sb.toString();
for (int i = 1; i < arr.length; i++) sb.append(separator).append(arr[i]);
return sb.toString();
}
Then you can do:
Use with AIint[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = myJoin(arr, " - ");
Java 8 Solution would be like this:
Use with AIStream.of(1,2,3,4).map(String::valueOf).collect(Collectors.joining("-"))