broment
broment

Reputation: 76

How would I create a String using a Character array in Java?

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.

Upvotes: 1

Views: 94

Answers (4)

VGR
VGR

Reputation: 44292

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.

Upvotes: 0

Alejandro Gonzalez
Alejandro Gonzalez

Reputation: 1371

/*
 * 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);
    }

}

Upvotes: 0

fabfas
fabfas

Reputation: 2228

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

Upvotes: 0

Jacob G.
Jacob G.

Reputation: 29680

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

Upvotes: 4

Related Questions