org.jhotdraw8.collection.mapped.MappedSpliterator Maven / Gradle / Ivy
Show all versions of org.jhotdraw8.collection Show documentation
/*
* @(#)MappedSpliterator.java
* Copyright © 2023 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.collection.mapped;
import org.jspecify.annotations.Nullable;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Maps a {@link Spliterator} to a different element type.
*
* The underlying iterator is referenced - not copied.
*
* @param the mapped element type
* @param the original element type
* @author Werner Randelshofer
*/
public class MappedSpliterator implements Spliterator {
private final Spliterator extends F> s;
private final Function mappingFunction;
private final int characteristics;
public MappedSpliterator(Spliterator extends F> s, Function mappingFunction, int characteristics) {
this.s = s;
this.mappingFunction = mappingFunction;
this.characteristics = characteristics;
}
public MappedSpliterator(Spliterator extends F> s, Function mappingFunction) {
this(s, mappingFunction, s.characteristics());
}
@Override
public boolean tryAdvance(Consumer super E> action) {
return s.tryAdvance(k -> action.accept(mappingFunction.apply(k)));
}
@Override
public @Nullable Spliterator trySplit() {
Spliterator extends F> split = s.trySplit();
return split == null ? null : new MappedSpliterator<>(split, mappingFunction, characteristics);
}
@Override
public long estimateSize() {
return s.estimateSize();
}
@Override
public int characteristics() {
return characteristics;
}
}