Saturday 4 January 2020

How to convert byte[] to List in Java?


By traversing the elements of array, you can convert byte array to List<Byte>.
public static List<Byte> getBoxedArray(byte[] arr) {
 if (arr == null)
  return null;

 List<Byte> result = new ArrayList<>();

 for (byte i : arr) {
  result.add(i);

 }
 return result;
}


App.java
package com.sample.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class App {

 private static void printElements(List<Byte> arr) {
  for (byte i : arr) {
   System.out.print(i + " ");
  }
  System.out.println();
 }

 public static List<Byte> getBoxedArray(byte[] arr) {
  if (arr == null)
   return null;

  List<Byte> result = new ArrayList<>();

  for (byte i : arr) {
   result.add(i);

  }
  return result;
 }

 public static void main(String args[]) throws IOException {
  byte[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };

  List<Byte> result1 = getBoxedArray(arr);
  printElements(result1);

 }

}

Output
1 3 5 7 2 4 6 8 10



You may like

No comments:

Post a Comment