In Java, I have an array of integers. Is there a quick way to convert them to a string?
I.E. int[] x = new int[] {3,4,5}
x toString() should yield "345"
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.
int[] x = new int[] {3,4,5};
String s = java.util.Arrays.toString(x).replaceAll("[\\,\\[\\]\\ ]", "")
Update
For completeness the Java 8 Streams solution, but it isn't pretty (libraries like vavr would be shorter and faster):
String s = IntStream.of(x)
.mapToObj(Integer::toString)
.collect(Collectors.joining(""));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With