tgoop.com/BookJava/4002
Create:
Last Update:
Last Update:
Stream Gathering with a Different Distinct Function
Статья обсуждает использование Gatherers в Java для определения собственной функции distinct. Автор предлагает альтернативный подход к стандартному методу distinct()
, который позволяет более гибко определять уникальность элементов в потоке, что иногда может быть очень полезно.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class DistinctifyGatherer {
public static <T> Gatherer<T, ?, T> of(
ToIntFunction<T> hashCode,
BiPredicate<T, T> equals,
BinaryOperator<T> merger) {
class Key {
private final T t;
public Key(T t) {this.t = t;}
public int hashCode() {
return hashCode.applyAsInt(t);
}
public boolean equals(Object obj) {
return obj instanceof Key that
&& equals.test(this.t, that.t);
}
}
return Gatherer.<T, Map<Key, Key>, T>ofSequential(
LinkedHashMap::new,
(state, element, _) -> {
var key = new Key(element);
var existing = state.get(key);
if (existing != null) {
key = new Key(merger.apply(
existing.t, key.t));
}
state.put(key, key);
return true;
},
(keys, downstream) -> keys.values().stream()
.takeWhile(_ -> !downstream.isRejecting())
.map(key -> key.t)
.forEach(downstream::push)
);
}
}
https://www.javaspecialists.eu/archive/Issue326-Stream-Gathering-with-a-Different-Distinct-Function.html
👉@BookJava
BY Библиотека Java разработчика

Share with your friend now:
tgoop.com/BookJava/4002