Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting List<Character> to char[] and then to String

Tags:

java

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.

like image 500
Rafiek Avatar asked Oct 09 '11 07:10

Rafiek


2 Answers

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));
like image 138
aioobe Avatar answered Oct 20 '22 05:10

aioobe


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);
like image 29
Alex Gitelman Avatar answered Oct 20 '22 05:10

Alex Gitelman