0
Sponsored Links


Ad by Google
Sometimes we required to convert Arrays to List or List to array in java while doing programming. In this post, I am going to show you how to convert List to Array in java.
You can convert List to Array in three different ways and those are listed below in ListUtil.java.

ListUtil.java
package com.javamakeuse.poc;

import java.util.ArrayList;
import java.util.List;

public class ListUtil {

 // For reference type or wrapper classes
 public static Integer[] getIntegerArray(List<Integer> numberList) {
  Integer[] numArray = new Integer[numberList.size()];
  return numberList.toArray(numArray);
 }

 // or
 public static String[] getStringArray(List<String> strList) {
  return strList.toArray(new String[strList.size()]);
 }

 // for primitive types
 public static int[] getPrimitiveArray(List<Integer> numberLsit) {
  int[] priArray = new int[numberLsit.size()];
  for (int i = 0; i < numberLsit.size(); i++) {
   priArray[i] = numberLsit.get(i);
  }
  return priArray;
 }

 public static void main(String[] args) {
  List<String> strList = new ArrayList<String>();
  strList.add("String1");
  strList.add("String2");

  // getting string array from string list
  String[] strArray = getStringArray(strList);

  // iterating string array
  for (int i = 0; i < strArray.length; i++) {
   System.out.println(strArray[i]);
  }
 }

}

OUT PUT:
String1
String2
Sponsored Links

0 comments:

Post a Comment