-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathComposite.java
More file actions
55 lines (44 loc) · 1.38 KB
/
Composite.java
File metadata and controls
55 lines (44 loc) · 1.38 KB
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.stream.StreamSupport;
interface ValueContainer extends Iterable<Integer> {
}
class SingleValue implements ValueContainer {
public int value;
// please leave this constructor as-is
public SingleValue(int value) {
this.value = value;
}
@Override
public Iterator<Integer> iterator() {
return Collections.singleton(value).iterator();
}
}
class ManyValues extends ArrayList<Integer> implements ValueContainer {
}
class MyList extends ArrayList<ValueContainer> {
int mySum = 0;
// please leave this constructor as-is
public MyList(Collection<? extends ValueContainer> c) {
super(c);
}
public int sum() {
return stream().flatMap(vc -> StreamSupport.stream(vc.spliterator(), false)).mapToInt(i -> i).sum();
}
}
class DemoComposite {
public static void main(String[] args) {
SingleValue v1 = new SingleValue(10);
SingleValue v2 = new SingleValue(30);
ManyValues v3 = new ManyValues();
v3.add(300);
v3.add(400);
MyList ml = new MyList(Arrays.asList(v1, v2, v3));
System.out.println("" + ml.sum());
}
public static void test(int i) {
}
}