'Copying Character array into char array
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?
Solution 1:[1]
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)
Solution 2:[2]
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.
Solution 3:[3]
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.
Solution 4:[4]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pejas |
Solution 2 | Ole V.V. |
Solution 3 | Joop Eggen |
Solution 4 | fozzybear |