Convert List or ArrayList of a String array in java
Example:
Input: list: [Ram, Shyam, Sheeta]
Output: [Ram, Shyam, Sheeta]
Approach: 1
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ConvertListToArray {public static void main(String[] args) {List<String> l = new ArrayList<String>();l.add("Ram");l.add("Shyam");l.add("Sheeta");String[] str = l.toArray(new String[l.size()]);System.out.println(Arrays.toString(str));}}
Approach: 2
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ConvertListToArray {public static void main(String[] args) {List<String> l = new ArrayList<String>();l.add("Ram");l.add("Shyam");l.add("Sheeta");String[] str = new String[l.size()];for (int i = 0; i < l.size(); i++) {str[i]=l.get(i);}System.out.println(Arrays.toString(str));}}
Approach: 3
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ConvertListToArray {public static void main(String[] args) {List<String> l = new ArrayList<String>();l.add("Ram");l.add("Shyam");l.add("Sheeta");// without size()String[] str = l.toArray(new String[0]);System.out.println(Arrays.toString(str));}}
Approach: 4- Using java 8
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ConvertListToArray {public static void main(String[] args) {List<String> l = new ArrayList<String>();l.add("Ram");l.add("Shyam");l.add("Sheeta");String[] str = l.stream().toArray(String[]::new);System.out.println(Arrays.toString(str));}}
Approach: 5-
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ConvertListToArray {public static void main(String[] args) {List<Employee> l = new ArrayList<Employee>();l.add(new Employee("Ram", 25));l.add(new Employee("Shyam", 30));l.add(new Employee("Sheeta", 20));Employee[] str = l.stream().toArray(Employee[]::new);System.out.println(Arrays.toString(str));Employee[] str1 = l.toArray(new Employee[0]);System.out.println(Arrays.toString(str1));}static class Employee {String name;int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Employee(String name, int age) {super();this.name = name;this.age = age;}@Overridepublic String toString() {return "Employee [name=" + name + ", age=" + age + "]";}}}
No comments:
Post a Comment