Java: Join Array of Primitives with Separator

Java: join array of primitives with separator

Here what I came up with. There are several way to do this and they are depends on the tools you using.


Using StringUtils and ArrayUtils from Common Lang:

int[] 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:

int[] 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 achive the result using streams.

Java 8's method String.join() works only with strings, so to use it you still have to convert int[] to String[].

String[] sarr = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new);
String result = String.join(" - ", sarr);

If you stuck using Java 7 or earlier with no libraries, you could write your own utility method:

public 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();
}

Than you can do:

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = myJoin(arr, " - ");

Java function for arrays like PHP's join()?

Starting from Java8 it is possible to use String.join().

String.join(", ", new String[]{"Hello", "World", "!"})

Generates:

Hello, World, !

Otherwise, Apache Commons Lang has a StringUtils class which has a join function which will join arrays together to make a String.

For example:

StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")

Generates the following String:

Hello, World, !

Join a list of object's properties into a String

To retrieve a String consisting of all the ID's separated by the delimiter "," you first have to map the Person ID's into a new stream which you can then apply Collectors.joining on.

String result = personList.stream().map(Person::getId)
.collect(Collectors.joining(","));

if your ID field is not a String but rather an int or some other primitive numeric type then you should use the solution below:

String result = personList.stream().map(p -> String.valueOf(p.getId()))
.collect(Collectors.joining(","));

java - StringUtils.join() returning pointer

Take a look at the signature for int arrays of StringUtils#join:

join(byte[] array, char separator)

You called join using

StringUtils.join(a, " "),

using a String instead of a char.
Try using

StringUtils.join(a, ' ')

instead.

What happened is that your call matched another signature:

join(T... elements),

so your arguments get interpreted as two objects, an integer array and a String with a space character. While creating the result string, the method concatenated the string representation of the integer array with the string.

Java print array of integers joined by spaces

Just loop over the array, and print each number.

for (int i: arr) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();

Convert array of strings into a string in Java

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.

Best way to convert an array of integers to a string in Java

Simplest performant approach is probably StringBuilder:

StringBuilder builder = new StringBuilder();
for (int i : array) {
builder.append(i);
}
String text = builder.toString();

If you find yourself doing this in multiple places, you might want to look at Guava's Joiner class - although I don't believe you'll be able to use it for primitive arrays. EDIT: As pointed out below, you can use Ints.join for this.

convert array to string java

There's no join method on arrays, instead you can use the stream API's joining collector:

Arrays.stream(arr)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" "));

Convert int array to string without commas in java

int[] arr = new int[]{2, 3, 4, 1, 5};
String res = Arrays.toString(arr).replaceAll("[\\[\\],]", "");
System.out.println(res);


Related Topics



Leave a reply



Submit