1

What would be the most efficient way to construct a new String using a Character[]? It's easy enough to do with the primitive char[], but unfortunately the String constructor does not include an option for Character[]. Converting to a char[] seems cumbersome. Is there any efficient way to construct the String with just the Character[]?

Thanks.

1
  • StringBuilder s = new StringBuilder(chars.length()) followed by a loop whose body calls s.append is as efficient as you’re likely to get. Any shorter solutions will be doing the equivalent at best. Commented Jan 17, 2020 at 0:10

4 Answers 4

4

One solution is to use a Stream with Collectors#joining:

Character[] chars = { 'H', 'e', 'l', 'l', 'o' };

String s = Arrays.stream(chars)
                 .map(Object::toString)
                 .collect(Collectors.joining());

System.out.println(s);

Output:

Hello
Sign up to request clarification or add additional context in comments.

Comments

0

One way of converting Character array to String

Character[] chars = { 'H', 'e', 'l', 'l', 'o' };

String str = Stream.of(chars)
             .map(String::valueOf)
             .collect(Collectors.joining());

System.out.println(str);

Ouput:

Hello

Comments

0
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

public class as {

    public static void main(String[] args) {
        Character[] chars = {'T', 'e', 'c', 'h', 'i', 'e', ' ',
            'D', 'e', 'l', 'i', 'g', 'h', 't'};

        StringBuilder word=new StringBuilder();
        for (Character char1 : chars) {
            word.append(char1);
        }
        System.out.println(word);
    }

}

1 Comment

The question is asking about Character[], not char[].
0

Is there any efficient way to construct the String with just the Character[]?

No. There are no constructors which can do that.

The most efficient approach is likely to be converting it to char[] as you yourself suggested:

char[] chars = new char[characters.length];
for (int i = characters.length - 1; i >= 0; i--) {
    chars[i] = characters[i];
}
String s = String.valueOf(chars);

Remember that “efficient” does not mean “stuffed into one line.” A Stream-based solution is going to be less efficient, because it will create (and eventually garbage-collect) a String for each Character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.