简体   繁体   中英

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.

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

}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM