How to convert String array to List

640
Mar 20, 2016

1. How to convert an array to a list if we are getting a list of Strings from other method or don't know the elements values of array

2. How make a List<String> if we have a some set of predefined string values.
If we have an array of Strings (returned from any other method) and now want to convert it to a List of Strings. java.util.Arrays utility class provides a method to convert an array to list.

Here is how we can convert it to List<String>

public class Test {
public static void main(String[] args) {
Test test = new Test();

// getting an array of numbers returned from method
String[] numberArray = test.getNumbers();

//converting to List
List<String> numberList = Arrays.asList(numberArray);

System.out.println(String.format("Size of numbers array is [%d] and size of numbersList is [%d].", numberArray.length, numberList.size()));
}

private String[] getNumbers() {
return new String[] {"one","two","three","four","five"};
}
}


Now lets consider an other situation, suppose we have a fixed set of String values and want to make a list of these values, then below are two approaches, and I would suggest second one over first



public class Test {
public static void main(String[] args) {
//suppose we have five values "one", "two", "three", "four" and "five"
// and want make a list of it.

//Approach 1
String numberArray[] = new String[] {"one", "two", "three", "four", "five"};

//converting to List
List<String> numberList = Arrays.asList(numberArray);

//Approach2
//use vararg feature Java 1.5 to make a list.
List<String> numberList2 = Arrays.asList("one", "two", "three", "four","five");

System.out.println(String.format("Size of numberList is [%d] and size of numberList2 is [%d].", numberList.size(), numberList2.size()));
}
}


Approach 2 uses the vararg feature of Java 1.5 to make a List without making a temporary array.

comments powered by Disqus

© Copyright 2017