【发布时间】:2017-11-26 06:32:01
【问题描述】:
我是 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;
【问题讨论】:
-
不。没有
ByteStream。但是由于字对齐,byte无论如何都不太可能是 8 位。您基于循环的方法简单、清晰且惯用 - 为什么要更改它? -
感谢您的回答。这可能是我无法使其工作的原因。然而,难道就没有办法做到这一点吗?使用类型转换或编写我自己的 ByteStream?
标签: java arrays java-8 byte java-stream