distinct方法应该使用空列表作为标识来调用reduce方法。如何使用累加器检查旧列表的值是否已在新列表中。
@Override
public <R> R reduce(R identity, BiFunction<R, ? super E, R> accumulator) {
for (E value : this) {
identity = accumulator.apply(identity, value);
}
return identity;
}
@Override
public List<E> distinct() {
List<E> list = new LinkedList<E>();
return reduce(list, (a, b) -> );
}
您应该使用contains
来检查元素是否在列表中。如果是,请不要将其添加到累加器,否则,请添加它。
return reduce(list, (acc, element) -> {
if (!acc.contains(element)) {
acc.add(element);
}
return acc;
});