2

I have a byte[] that I would like to represent as a List where the elements are the plain value of each individual byte, for example if I have

byte[] buf; //filled elsewhere
System.out.println(Arrays.toString(buf)); //prints [97, 99, -100]

I want to end up with an object equivalent to

new ArrayList<Long>{97, 99, -100};

How can I make this object from my original buf?

2 Answers 2

2

Java 8:

byte[] buf = { 97, 99, -100 };
List<Long> list = LongStream.range(0, buf.length).map(i -> buf[(int) i]).boxed().collect(Collectors.toList());
System.out.println(list);

output:

[97, 99, -100]
Sign up to request clarification or add additional context in comments.

Comments

0

I can't think of any utility that can cast an array of one object type to a different object type. You can either get a List of bytes by using:

List<Byte> bytes = Arrays.asList(buf);

Or make your own utility method similar to:

public static List<Long> bytesToListOfLongs(byte[] bytes) {
    List<Long> longs = new ArrayList<Long>();
    longs.ensureCapacity(bytes.length);

    for (byte b: bytes) {
        longs.add(new Long(b));
    }

    return longs;
}

And later use it like:

    byte[] buf; //filled elsewhere
    List<Long> longs = bytesToListOfLongs(buf);

1 Comment

Note that casting b in bytesToListOfLongs method to long as in (long)b might be necessary. It's a widening primitive conversion though, so I'm not sure about it and I can't test it at the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.