-
Notifications
You must be signed in to change notification settings - Fork 463
/
ListToArray.java
45 lines (29 loc) · 971 Bytes
/
ListToArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Java: convert ArrayList<String> to String[]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.*;
class ListToArray {
public static void main(String[] args) {
// create Array
String[] array = {"Bugatti", "Ferarri", "Lamborghini", "Rolls Royce"};
// 3 ways to print Array
System.out.println(Arrays.toString(array));
for(String s : array) {
System.out.print(s + ", ");
}
System.out.println();
Stream.of(array)
.forEach(System.out::println);
// 2 ways to convert Array to ArrayList
List<String> arrayList = new ArrayList<>(Arrays.asList(array));
System.out.println("arrayList: " + arrayList);
List<String> arrayList2 = new ArrayList<>(List.of(array));
System.out.println("arrayList2: " + arrayList2);
// convert ArrayList to Array
String[] array2 = arrayList.toArray(new String[0]);
// print Array
Stream.of(array2)
.forEach(System.out::println);
}
}