1.

What are the ways to convert an array of strings to list and list of strings to array of strings?

Answer»

Arrays class of java.util package contains asList() which helps to convert an array of strings to List. This method bridges between array-based and collection-based APIS. The returned List is serializable and implements RandomAccess

  • Below is the code snippet :
PUBLIC static void main (String[] args) { String[] names = { " KOLKATA", "Bangalore", "Canada", "Australis" }; List<String> nameList = names.asList(); System.out.println(nameList); for(String name : names ) { System.out.println(name); } } Using toArray() of List method, we can convert List of Strings to Array of Strings
  • List of String to Array of String
Public static void main (String[] args) { List<String> list = Arrays.asList("Bangalore", "Kolkata"); String[] nameArray = list.toArray(new String[0]); System.out.println(Arrays.toString(nameArray)); }


Discussion

No Comment Found