Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

like image 358
didxga Avatar asked Nov 28 '22 11:11

didxga


2 Answers

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.

like image 186
Jon Skeet Avatar answered Dec 04 '22 10:12

Jon Skeet


   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(""));
like image 25
Landei Avatar answered Dec 04 '22 10:12

Landei