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.
In Java 8+ you could use an
IntStream
and aStringJoiner
. Something like,Output is (as requested)
Here what I came up with. There are several way to do this and they are depends on the tools you using.
Using
StringUtils
andArrayUtils
from Common Lang:You can't just use
StringUtils.join(arr, " - ");
becauseStringUtils
doesn't have that overloaded version of method. Though, it has methodStringUtils.join(int[], char)
.Works at any Java version, from 1.2.
Using Java 8 streams:
Something like this:
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 convertint[]
toString[]
.If you stuck using Java 7 or earlier with no libraries, you could write your own utility method:
Than you can do:
I've been looking for a way to join primitives in a Stream without first instantiating strings for each one of them. I've come to this but it still requires boxing them.
You can use Guava for joining elements. More examples and docs you can find there. https://github.com/google/guava/wiki/StringsExplained
To be more precise you should firstly wrap your array into a
List
withArrays.asList()
or Guava's primitive-friendly equivalents.I'm sure there's a way to do this in Kotlin/Scala or other JVM languages as well but you could always stick to keeping things simple for a small set of values like you have above: