我们可以使用Stream
API从包装对象的对应项创建原始类型数组。
将Character[]
数组转换为char[]
,使用相应大小分配的自定义Collector
、Supplier<CharBuffer>
、BiConsumer<CharBuffer, Character>
累加器、BinaryOperator<CharBuffer>
合并器和Function<CharBuffer,char[]>
完成器),如下操作即可:
Collector<Character, CharBuffer, char[]> charArrayCollector = Collector.of(
() -> CharBuffer.allocate(95),
CharBuffer::put,
CharBuffer::put,
CharBuffer::array
);
它为可打印ASCII字符提供CharBuffer
,将每个流式字符累积到CharBuffer实例中,以正确顺序组合来自多个CharBuffer实例的并行处理结果,最终从累积和组合的结果中构建所需的char[]
数组,待所有线程完成后。
首先,我们通过利用IntStream中的int值从标准可打印ASCII字符集中迭代ASCII范围,并将每个值映射到Character Stream来创建一个Character[]测试数组。在将它们转换为char原语并将其转换为Character对象之后:
Character[] asciiCharacters = IntStream.range(32, 127)
.mapToObj(i -> Character.valueOf((char)i))
.toArray(Character[]::new);
现在,我们只需要从数组创建字符的,然后通过自定义收集器收集到数组中。
char[] asciiChars = Stream.of(asciiCharacters ).collect(charArrayCollector);
这同样适用于其他Number
类型:
byte[] bytes = new byte[] { Byte.MIN_VALUE, -1 , 0, 1, Byte.MAX_VALUE };
Byte[] boxedBytes = IntStream.range(0, bytes.length)
.mapToObj(i -> bytes[i])
.toArray(Byte[]::new);
byte[] collectedBytes = Stream.of(boxedBytes).collect(
Collector.of(
() -> ByteBuffer.allocate(boxedBytes.length),
ByteBuffer::put,
ByteBuffer::put,
ByteBuffer::array
)
);
short[] shorts = new short[] { Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE };
Short[] boxedShorts = IntStream.range(0, shorts.length)
.mapToObj(i -> shorts[i])
.toArray(Short[]::new);
short[] collectedShorts = Stream.of(boxedShorts).collect(
Collector.of(
() -> ShortBuffer.allocate(boxedShorts .length),
ShortBuffer::put,
ShortBuffer::put,
ShortBuffer::array
)
);
float[] floats = new float[] { Float.MIN_VALUE, -1.0f, 0f, 1.0f, Float.MAX_VALUE };
Float[] boxedFLoats = IntStream.range(0, floats.length)
.mapToObj(i -> floats[i])
.toArray(Float[]::new);
float[] collectedFloats = Stream.of(boxedFLoats).collect(
Collector.of(
() -> FloatBuffer.allocate(boxedFLoats.length),
FloatBuffer::put,
FloatBuffer::put,
FloatBuffer::array
)
);
原始类型,Stream
API 支持它,可以更容易地进行转换:
int[] ints = new int[] { Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE };
Integer[] integers = IntStream.of(ints).boxed().toArray(Integer[]::new);
int[] collectedInts = Stream.of(integers).collect(
Collector.of(
() -> IntBuffer.allocate(integers.length),
IntBuffer::put,
IntBuffer::put,
IntBuffer::array
)
);
long[] longs = new long[] { Long.MIN_VALUE, -1l, 0l, 1l, Long.MAX_VALUE };
Long[] boxedLongs = LongStream.of(longs).boxed().toArray(Long[]::new);
long[] collectedLongs = Stream.of(boxedLongs ).collect(
Collector.of(
() -> LongBuffer.allocate(boxedLongs .length),
LongBuffer::put,
LongBuffer::put,
LongBuffer::array
)
);
double[] doubles = new double[] { Double.MIN_VALUE, -1.0, 0, 1.0, Double.MAX_VALUE };
Double[] boxedDoubles = DoubleStream.of(doubles)
.boxed()
.toArray(Double[]::new);
double[] collectedDoubles = Stream.of(boxedDoubles).collect(
Collector.of(
() -> DoubleBuffer.allocate(boxedDoubles.length),
DoubleBuffer::put,
DoubleBuffer::put,
DoubleBuffer::array
)
);