Eternal Noob
Eternal Noob

Reputation: 2807

converting an array of bytes to List<Byte>

I could think of these things,

  1. Arrays.asList(byte[]) converts byte[] to List<byte[]>,
  2. looping through byte array and add each element to list

I was just wondering Is there any library function to do that?

Upvotes: 48

Views: 61667

Answers (6)

fps
fps

Reputation: 31

Java 8 one-line byte[] to List<Byte> conversion, given array as input:

List<Byte> list = IntStream.range(0, array.length).mapToObj(i -> array[i]).collect(Collectors.toList());

Upvotes: 3

Datz
Datz

Reputation: 3841

I think the simplest pure Java way, without additional libraries, is this:

private static List<Byte> convertBytesToList(byte[] bytes) {
    final List<Byte> list = new ArrayList<>();
    for (byte b : bytes) {
        list.add(b);
    }
    return list;
}

But better check twice if you really need to convert from byteto Byte.

Upvotes: 1

Ammar
Ammar

Reputation: 1

byte[] byteArray;
List<Byte> medianList=new ArrayList<>(); 
int median=0,count=0;
Path file=Paths.get("velocities.txt");
if(Files.exists(file)){
    byteArray=Files.readAllBytes(file);
}
medianList.addAll(Arrays.asList(byteArray));

Upvotes: 0

peenut
peenut

Reputation: 3426

Library Apache Commons Lang has ArrayUtils.toObject, which turns a primitive array to a typed object array:

int array[] = { 1, 2, 3 };
List<Integer> list = Arrays.asList(ArrayUtils.toObject(array));

Upvotes: 22

Jens Nyman
Jens Nyman

Reputation: 1216

As this post suggests: the guava Bytes class can help out:

byte[] bytes = ...
List<Byte> byteList = Bytes.asList(bytes);

Upvotes: 20

chkal
chkal

Reputation: 5668

For Byte[] instead of byte[] this would work:

  Byte[] array = ....
  List<Byte> list = Arrays.asList(array);

Upvotes: 18

Related Questions