How can I make an IntStream from a byte array?

北城余情 提交于 2019-12-06 01:14:27

问题


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?


回答1:


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.




回答2:


You could do something like

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

but it's not very pretty. (It's not so bad though: usage of AtomicInteger allows the stream to be run in parallel.)




回答3:


One line code:

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


来源:https://stackoverflow.com/questions/27181026/how-can-i-make-an-intstream-from-a-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!