I already know there are only IntStream
and LongStream
. How can I make an IntStream
from a byte array?
Currently I'm planning to do like this.
static int[] bytesToInts(final byte[] bytes) {
final int[] ints = new int[bytes.length];
for (int i = 0; i < ints.length; i++) {
ints[i] = bytes[i] & 0xFF;
}
return ints;
}
static IntStream bytesToIntStream(final byte[] bytes) {
return IntStream.of(bytesToInt(bytes));
}
Is there any easier or faster way to do this?
A good way to turn an array into a stream is to use the Arrays class' stream() method. This works the same for both primitive types and objects.
Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
A variant of Radiodef's answer:
static IntStream bytesToIntStream(byte[] bytes) {
return IntStream.range(0, bytes.length)
.map(i -> bytes[i] & 0xFF)
;
}
Easier to guarantee parallelization, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With