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?
-
What about unboxing?Przemysław Moskal– Przemysław Moskal2017-11-15 14:54:38 +00:00Commented 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 meleedwon– leedwon2017-11-15 15:05:03 +00:00Commented Nov 15, 2017 at 15:05
-
Ok, thanks for pointing it out.Przemysław Moskal– Przemysław Moskal2017-11-15 15:44:26 +00:00Commented Nov 15, 2017 at 15:44
4 Answers
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.
Comments
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
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
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();