6

How can the Array content be converted to a String in Java?

Example:

int[] myArray = {1,2,3};

The output has to be:

"123"

Arrays.toString(myArray) is returning:

"[1, 2, 3]"

and myArray.toString(), returns:

[I@12a3a380

So none of them works. Is there a function for this?

This question might look similar to (this), but is actually different. I am literally asking for a String made of all the array entries.

Giacomo
  • 551
  • 2
  • 4
  • 16
  • 1
    you don't want the array converted to a String. you want the elements converted to String, and then concatenated. I think iterating over the array would be the easiest way to implement this – Stultuske Sep 07 '18 at 13:20
  • 1
    `IntStream.of(myArray).mapToObj(Integer::toString).collect(joining(""))`. – Andy Turner Sep 07 '18 at 13:22
  • @Zabuza it doesn;t work.. Compile will fail...!! – miiiii Sep 07 '18 at 13:25
  • 2
    @AndyTurner `IntStream.of(myArray)` just calls `Arrays.stream` internally... and I don't think this is a duplicate on how to *print* the contents of an array, this does not look like a duplicate to me – Eugene Sep 07 '18 at 13:25
  • "_Is there a function that does what I am trying to do without looping through the array and do it manually?_" no because this would not make much sense to provide a method that "specific". You could do it with a `String` array with `String.join` – AxelH Sep 07 '18 at 13:30

4 Answers4

13
String joined = Arrays.stream(myArray)
            .mapToObj(String::valueOf)
            .collect(Collectors.joining(""));

System.out.println(joined);   
Eugene
  • 117,005
  • 15
  • 201
  • 306
7

The old-fashioned way:

StringBuilder builder = new StringBuilder();
for (int value : myArray) {
  builder.append(value);
}
... now use builder.toString()

Less fancy compared to the stream solution, but on the other hand: in case runtime performance matters, this here should beat any other approach.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
6

A curveball approach is to remove any non-digit character from the ouput of one of the traditional serialization methods:

Arrays.toString(myArray).replaceAll("\\D", "");

which yields 123 in your example.

replaceAll replaces all positive matches of the regular expression in the first parameter with the contents of the second parameter. \D is regex for anything that is not a digit.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
3

I will go old school, which works every time no matter what as follows:

String myString = "";
for(int val : myArray)
{
  myString += val;
}

System.out.println(myString); // To check the output of myString

Will work! Hope this helps!

Note: This will work in Embedded Java as well where StringBuilder and some other classes are stripped for embedded devices.

Somdip Dey
  • 3,346
  • 6
  • 28
  • 60