How can I make an IntStream from a byte array?

2020-07-10 03:03发布

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?

3条回答
男人必须洒脱
2楼-- · 2020-07-10 03:37

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.

查看更多
老娘就宠你
3楼-- · 2020-07-10 03:38

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

查看更多
\"骚年 ilove
4楼-- · 2020-07-10 03:40

One line code:

import com.google.common.primitives.Bytes;
IntStream in = Bytes.asList(bytes).stream().mapToInt(i-> i & 0xFF);
查看更多
登录 后发表回答