zella
zella

Reputation: 4685

How remove duplicates based on previous emission in List item

I have an Observable of Lists:

Observable<List<String>> source = Observable.just(
        List.of("a", "c", "e"),
        List.of("a", "b", "c", "d"),
        List.of("d", "e", "f")
);

How to remove duplicates so:

[a,c,e][a,b,c,d][d,e,f] => [a,c,e][b,d][f]

It's ok for me to accumulate previous emissions, just need transformation like above.

Upvotes: 0

Views: 115

Answers (1)

zella
zella

Reputation: 4685

I implemented it with scan operator and helper class, that stores current and previous values:

static class Distinct {
    final HashSet<String> previous;
    final List<String> current;

    public Distinct(HashSet<String> previous, List<String> current) {
        this.previous = previous;
        this.current = current;
    }
}

Observable<List<String>> source = Observable.just(
        List.of("a", "c", "e"),
        List.of("a", "b", "c", "d"),
        List.of("d", "e", "f")
);

source.scan(new Distinct(new HashSet<>(), new ArrayList<>()), (acc, item) -> {
    var newItem = new ArrayList<String>();
    item.forEach(i -> {
        if (acc.previous.add(i))
            newItem.add(i);
    });
    return new Distinct(acc.previous, newItem);
})
        .skip(1)
        .map(md -> md.current)
        .subscribe(System.out::println);

Output:

[a, c, e]
[b, d]
[f]

Upvotes: 1

Related Questions