I've tried the following:
List<Character> randomExpression = new ArrayList<Character>();
String infixString = new String(randomExpression.toArray());
But this won't work because there is no String conctructor with an Object[]
parameter.
As you've probably noted, char[]
is something different than Character[]
, and there's no immediate way of transforming one to another in the standard API.
In this particular situation, I'd probably go with something like:
String result = chars.stream()
.map(String::valueOf)
.collect(Collectors.joining());
Or, pre Java 9:
StringBuilder sb = new StringBuilder(chars.size());
for (char c : chars)
sb.append(c);
String result = sb.toString();
An alternative is to use the Apache Commons method ArrayUtils.toPrimitive
:
List<Character> chars = new ArrayList<Character>();
// ...
Character[] charArr = chars.toArray(new Character[chars.size()]);
String str = new String(ArrayUtils.toPrimitive(charArr));
String
will need array of primitive char
anyway and you can't convert Character[] to char[] directly. So your best bet is to iterate through list and build char[]
array to pass to new String(char[])
.
In code it would be something like this:
char[] tmp = new char[randomExpression.size()];
for (int i = 0; i < tmp.length; i++) {
tmp[i]=randomExpression.get(i);
}
String infixString = new String(tmp);
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