0

Hi I want to fast copy array of Characters to array of chars I can write a method that copies Character array into char array, by converting every Charater in array to char but is there any ready method which is faster just as Arrays.copyOf for two arrays of same type?

3
  • What about unboxing? Commented Nov 15, 2017 at 14:54
  • It surely would work but in that case I would have to create new Char array and just fill it with data from Character array and I'm looking for some ready method that will make that for me Commented Nov 15, 2017 at 15:05
  • Ok, thanks for pointing it out. Commented Nov 15, 2017 at 15:44

4 Answers 4

4
    char[] myCharArray = Arrays.stream(myCharacterArray)
            .map(ch -> ch.toString())
            .collect(Collectors.joining())
            .toCharArray();

It was fast to write. Whether it will execute fast? Unless you have a very big array or do this conversion often, you shouldn‘t need to care.

The answer by fozzybear presents a variant of the same that you may also consider.

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

Comments

2

There is method in Apache Commons Lang which does exactly what you need: http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#toPrimitive-java.lang.Character:A-

public static char[] ArrayUtils.toPrimitive(Character[] array)

Comments

0

Technical not possible, but you might do with a lazy kind of unboxing Character to char. For instance using a Stream. (Which at the moment might even be additional overhead.)

If the Character array stems from a Collection, a List, then you just might take measures at the source. Though all will not be fast. But an array of Character is not sophisticated, like wrapping every coin in its own piece of paper.

Comments

0

Given a Character[] array

Character[] asciiChars = Stream.iterate(32, i -> i += 1)
                         .map(i -> Character.valueOf((char)i.intValue()))
                         .limit(95)
                         .toArray(Character[]::new);

A similar Stream-based solution to the example above, saving one mapping step, would be:

char[] chars = Stream.of(asciiChars)
               .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
               .toString()
               .toCharArray();

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.