-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayListDemo3.java
74 lines (60 loc) · 2.18 KB
/
ArrayListDemo3.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class MyClass {
private int id;
private String name;
MyClass(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return this.id + ", " + this.name;
}
}
public class ArrayListDemo3 {
public static void main(String args[]) {
// create an array list
List<MyClass> al = new ArrayList<>();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add(new MyClass(1, "Rodgers"));
al.add(new MyClass(2, "Bradley"));
al.add(new MyClass(3, "Chambers"));
al.add(new MyClass(4, "Calvin"));
al.add(new MyClass(5, "Quinn"));
al.add(new MyClass(6, "Mccoy"));
System.out.println("Size of al after additions: " + al.size());
// iterate
for (int i = 0; i < al.size(); i++) {
MyClass mc = al.get(i);
System.out.println(mc.getId() + ", " + mc.getName());
}
System.out.println("");
/*
List<Integer> names = new ArrayList<>();
for (int i = 0; i < al.size(); i++) {
MyClass mc = al.get(i);
if (mc.getId() % 2 == 0)
names.add(mc.getId());
}
*/
// streams with map, filter, and collect
List<String> nameList = al.stream().map(MyClass::getName).collect(Collectors.toList());
nameList.forEach(e -> System.out.print(e + " "));
System.out.println();
List<Integer> evenIdList = al.stream().map(MyClass::getId).filter(e -> (e % 2 == 0)).collect(Collectors.toList());
evenIdList.forEach(e -> System.out.print(e + " "));
System.out.println();
List<MyClass> evenIdObjectList = al.stream().filter(e -> (e.getId() % 2 == 0)).collect(Collectors.toList());
evenIdObjectList.forEach(e -> System.out.println(e + " "));
System.out.println();
}
}