Write a java program to convert ArrayList to String Array. how to convert ArrayList into the string array in java
Write a program that performs the following actions:
Read n strings as input.
Create an arraylist to store the above n strings in this arraylist.
Write a function convertToStringArray which accepts the arraylist as input.
The function should sort the elements (strings) present in the arraylist and convert them into a string array.
Return the array.
Input and Output Format:
Input consists of n+1 integers. The first integer denotes the size of the arraylist, the next n strings are values to the arraylist.
Output consists of an arrayas per step 4.
Refer sample output for formatting specifications.
Sample Input 1:
4
a
d
c
b
Sample Output 1:
a
b
c
d
java program to convert ArrayList to String Array
import java.util.*; public class Main { public static void main(String[] args) { List<String> l1=new ArrayList<String>(); l1.add("Apple"); l1.add("Chery"); l1.add("Grapes"); List<String> l2=new ArrayList<String>(); l2.add("Orange"); l2.add("Mango"); l2.add("Melon"); l2.add("Apple"); String[] s2=fruitsList(l1,l2); for(String s3:s2) System.out.println(s3); } public static String[] fruitsList(List<String> l1, List<String> l2){ List<String> l3=new ArrayList<String>(); for(int i=0;i<l1.size();i++){ String s1=l1.get(i); if(s1.charAt(s1.length()-1)!='a' && s1.charAt(s1.length()-1)!='A' && s1.charAt(s1.length()-1)!='e' && s1.charAt(s1.length()-1)!='E') l3.add(s1); } for(int i=0;i<l2.size();i++){ String s1=l2.get(i); if(s1.charAt(0)!='m' && s1.charAt(0)!='M' && s1.charAt(0)!='a' && s1.charAt(0)!='A') l3.add(s1); } Collections.sort(l3); String[] s2=new String[l3.size()]; for(int i=0;i<s2.length;i++) s2[i]=l3.get(i); return s2; }