How can I make an IntStream from a byte array?

随声附和 提交于 2019-12-04 05:05:45

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.

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.)

One line code:

import com.google.common.primitives.Bytes;
IntStream in = Bytes.asList(bytes).stream().mapToInt(i-> i & 0xFF);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!