我是 Java 8 流的新手,我想知道是否有办法对返回 byte
并接受 int 的方法执行
作为参数。forEach/map
调用
例子:
public class Test {
private byte[] byteArray; // example of byte array
public byte getByte(int index) {
return this.byteArray[index];
}
public byte[] getBytes(int... indexes) {
return Stream.of(indexes)
.map(this::getByte) // should return byte
.collect(byte[]::new); // should return byte[]
}
}
您可能猜到了,getBytes
方法不起作用。 "int[] cannot be converted to int"
可能某处缺少 foreach,但个人无法弄清楚。
但是,这是有效的老式方法,我想将其重写为 Stream。
byte[] byteArray = new byte[indexes.length];
for ( int i = 0; i < byteArray.length; i++ ) {
byteArray[i] = this.getByte( indexes[i] );
}
return byteArray;
最佳答案
您可以编写自己的 Collector
并使用 ByteArrayOutputStream
构建您的 byte[]
:
final class MyCollectors {
private MyCollectors() {}
public static Collector<Byte, ?, byte[]> toByteArray() {
return Collector.of(ByteArrayOutputStream::new, ByteArrayOutputStream::write, (baos1, baos2) -> {
try {
baos2.writeTo(baos1);
return baos1;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}, ByteArrayOutputStream::toByteArray);
}
}
并使用它:
public byte[] getBytes(int... indexes) {
return IntStream.of(indexes).mapToObj(this::getByte).collect(MyCollectors.toByteArray());
}
关于java - 如何使用 Java 8 Stream 映射和收集原始返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44708532/