Converting 'ArrayList<String> to 'String[]' in Java
Example:
Input: list=[Ram, Shyam] Output: [Ram, Shyam]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ArrayListToStringArray {public static void main(String[] args) {List<String> list = new ArrayList<String>();list.add("Ram");list.add("Shyam");String[] stringArray = list.toArray(new String[0]);System.out.println(Arrays.toString(stringArray));}}
Approach: java 8
Java
import java.util.Arrays;import java.util.List;public class ArrayListToStringArray {public static void main(String[] args) {List<String> list = List.of("Ram", "Shyam");String[] strings = list.stream().toArray(String[]::new);System.out.println(Arrays.toString(strings));}}
Approach: java 11+
Java
import java.util.Arrays;import java.util.List;public class ArrayListToStringArray {public static void main(String[] args) {List<String> list = List.of("Ram", "Shyam");String[] strings = list.toArray(String[]::new);System.out.println(Arrays.toString(strings));}}
Approach: Using toArray()
Java
import java.util.Arrays;import java.util.List;public class ArrayListToStringArray {public static void main(String[] args) {List<String> list = List.of("Ram", "Shyam");Object[] objectList = list.toArray();String[] stringArray = Arrays.copyOf(objectList, objectList.length, String[].class);System.out.println(Arrays.toString(stringArray));}}
No comments:
Post a Comment