-
Notifications
You must be signed in to change notification settings - Fork 1
/
CompositeCodingExercise.java
66 lines (53 loc) · 1.45 KB
/
CompositeCodingExercise.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
// Exercise for composite section -
package structural.composite;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
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>
{
// please leave this constructor as-is
public MyList(Collection<? extends ValueContainer> c)
{
super(c);
}
public int sum()
{
int sum = 0;
for (ValueContainer element: this) {
for (int num : element)
{
sum = sum + num;
}
}
return sum;
}
}
class CompositeExerciseDemo
{
public static void main(String[] args) {
SingleValue value = new SingleValue(1);
SingleValue value1 = new SingleValue(5);
SingleValue value2 = new SingleValue(10);
ManyValues list = new ManyValues();
list.addAll(Arrays.asList(30, 2, new SingleValue(1).value));
MyList compositeList = new MyList(List.of(value, value1, value2, list));
System.out.println(compositeList.sum());
}
}