How can I make an intstream from an array of bytes?

I already know that there is only IntStream and LongStream . How can I make an IntStream from an array of bytes?

I am currently planning to do so.

 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 an easier or faster way to do this?

+6
source share
3 answers

Radiodef answer option:

 static IntStream bytesToIntStream(byte[] bytes) { return IntStream.range(0, bytes.length) .map(i -> bytes[i] & 0xFF) ; } 

It is easier to guarantee parallelization.

+7
source

You can do something like

 static IntStream bytesToIntStream(byte[] bytes) { AtomicInteger i = new AtomicInteger(); return IntStream .generate(() -> bytes[i.getAndIncrement()] & 0xFF) .limit(bytes.length); } 

but it is not very beautiful. (This is not so bad: using AtomicInteger allows the AtomicInteger to run in parallel.)

+1
source

One line code:

 import com.google.common.primitives.Bytes; IntStream in = Bytes.asList(bytes).stream().mapToInt(i-> i & 0xFF); 
+1
source

Source: https://habr.com/ru/post/978813/


All Articles