Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: join array of primitives with separator

Suppose, I have an array:

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7}; 

And I need to join its elements using separator, for example, " - ", so as the result I should get string like this:

"1 - 2 - 3 - 4 - 5 - 6 - 7" 

How could I do this?

PS: yes, I know about this and this posts, but its solutions won't work with an array of primitives.

like image 538
spirit Avatar asked Jul 17 '16 20:07

spirit


People also ask

Which method joins all array elements into string with specified separator?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.

How do I join an int array?

Ints join() function | Guava | Java For example, join(“-“, 1, 2, 3) returns the string “1-2-3”. Parameters: This method takes the following parameters: separator: The text that should appear between consecutive values in the resulting string (but not at the start or end). array: An array of int values.

What is StringUtils join in Java?

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.


1 Answers

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, " - "); 
like image 147
spirit Avatar answered Sep 20 '22 19:09

spirit