如何使用自己的reduce方法来区分列表

问题描述 投票:2回答:1

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) -> );
}
java lambda
1个回答
3
投票

您应该使用contains来检查元素是否在列表中。如果是,请不要将其添加到累加器,否则,请添加它。

return reduce(list, (acc, element) -> {
    if (!acc.contains(element)) {
        acc.add(element);
    }
    return acc;
});
© www.soinside.com 2019 - 2024. All rights reserved.