How to use own reduce method to distinct list

Armin Zierlinger :

The distinct method should call the the reduce method with a empty list as identity. How can I use the accumulator to check if a value of the old list is already in the new list.

@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) -> );
}
Sweeper :

You should use contains to check if an element is in the list. If it is, don't add it to the accumulator, otherwise, do add it.

return reduce(list, (acc, element) -> {
    if (!acc.contains(element)) {
        acc.add(element);
    }
    return acc;
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135635&siteId=1