Skip to content

Commit

Permalink
Add MoreGatherers.distinctByKeepLast() (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit authored Oct 11, 2024
1 parent 6a27ce6 commit f6bb76b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ Provided `Gatherers`:
- `MoreGatherers.zipWithIterable(Iterable<T2>)`
- `MoreGatherers.zipWithIterable(Iterable<T2>, BiFunction<T1,T2>)`
- `MoreGatherers.distinctBy(Function<T, R>)`
- `MoreGatherers.distinctByKeepLast(Function<T, R>)`
- `MoreGatherers.distinctUntilChanged()`
- `MoreGatherers.distinctUntilChanged(Function<T, R>)`
17 changes: 17 additions & 0 deletions src/main/java/com/pivovarit/gatherers/MoreGatherers.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
Expand Down Expand Up @@ -56,6 +57,22 @@ private MoreGatherers() {
));
}

public static <T, U> Gatherer<T, ?, T> distinctByKeepLast(Function<? super T, ? extends U> keyExtractor) {
Objects.requireNonNull(keyExtractor, "keyExtractor can't be null");
return Gatherer.ofSequential(
LinkedHashMap<U, T>::new,
(state, element, _) -> {
state.put(keyExtractor.apply(element), element);
return true;
},
(state, downstream) -> {
for (T element : state.values()) {
downstream.push(element);
}
}
);
}

public static <T, U> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
Objects.requireNonNull(keyExtractor, "keyExtractor can't be null");
return Gatherer.ofSequential(
Expand Down
29 changes: 29 additions & 0 deletions src/test/java/com/pivovarit/gatherers/DistinctByKeepLastTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.pivovarit.gatherers;

import org.junit.jupiter.api.Test;

import java.util.stream.Stream;

import static com.pivovarit.gatherers.MoreGatherers.distinctByKeepLast;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class DistinctByKeepLastTest {

@Test
void shouldDistinctByEmptyStream() {
assertThat(Stream.empty().gather(distinctByKeepLast(i -> i))).isEmpty();
}

@Test
void shouldDistinctBy() {
assertThat(Stream.of("a", "bb", "cc", "ddd")
.gather(distinctByKeepLast(String::length)))
.containsExactly("a", "cc", "ddd");
}

@Test
void shouldRejectNullExtractor() {
assertThatThrownBy(() -> distinctByKeepLast(null)).isInstanceOf(NullPointerException.class);
}
}

0 comments on commit f6bb76b

Please sign in to comment.