I am tasked to implement a custom class to mimic to properties of a Set (without using any data structures of Sets). As such, I chose to store the elements of type T into an ArrayList as a field for the class.
class CustomSet<T> {
private final ArrayList<T> elementList;
CustomSet() { // when initialising an empty set
this.elementList = new ArrayList<>();
}
private CustomSet(ArrayList<T> otherElementList) { // When passing in a list to construct the set
this.elementList = otherElementList;
}
static <T> CustomSet<T> of(T...elem) {
ArrayList<T> set = new ArrayList<>();
for (T e: elem) {
set.add(e);
}
return new CustomSet<T>(set);
}
// typical add, clear, remove functions for the set which can be done with methods in ArrayList
}
One of my task is to implement a reduce function which takes in a seed and a binary operator to return the reduced value (without the use of explicit loops i.e use streams) such that the following is observed
CustomSet<Integer> thisSet = CustomSet.of(1,2,3,4,5,6);
thisSet.reduce(0, (subtotal, element) -> subtotal + element) // outputs 21
CustomSet<String> otherSet = CustomSet.of("a", "b", "c", "d", "e");
otherSet.reduce("", (partialString, element) -> partialString + element); // outputs "abcde"
I have tried to write my code as such
<U> U reduce(U identity, BiFunction<U, ? super T, U> acc) {
return elementsList.stream().reduce(identity, acc, (x,y) -> x + y);
// error which says Operator "+" cannot be applied to 'U', 'U'
}
However it runs to the following error above. How do I solve this?
EDIT
It would be the same as converting the code below to one which uses streams
<U> U reduce(U identity, BiFunction<U, ? super T, U> acc) {
for (T ele: elementsList) {
identity = acc.apply(identity, ele);
}
return identity;
}