Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an IntStream from a byte array?

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?

like image 701
Jin Kwon Avatar asked Nov 28 '14 02:11

Jin Kwon


People also ask

How do I turn an array into a stream?

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.

How do you turn a byte into a string?

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.

How do you turn an object into a ByteArray?

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.


1 Answers

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.

like image 199
srborlongan Avatar answered Sep 22 '22 05:09

srborlongan