Saturday 4 January 2020

How to convert short[] to List in Java?


By traversing the elements of array we can convert short array to List<Short>.
public static List<Short> getBoxedList(short[] arr) {
 if (arr == null)
  return null;

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

 for (short 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<Short> arr) {
  for (short i : arr) {
   System.out.print(i + " ");
  }
  System.out.println();
 }

 public static List<Short> getBoxedList(short[] arr) {
  if (arr == null)
   return null;

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

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

  }
  return result;
 }

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

  List<Short> result1 = getBoxedList(arr);
  printElements(result1);

 }
}

Output
1 3 5 7 2 4 6 8 10


You may like

No comments:

Post a Comment