diff --git a/src/main/java/gr/james/sampling/IdentityRandomSampling.java b/src/main/java/gr/james/sampling/IdentityRandomSampling.java new file mode 100644 index 0000000..704a3d3 --- /dev/null +++ b/src/main/java/gr/james/sampling/IdentityRandomSampling.java @@ -0,0 +1,87 @@ +package gr.james.sampling; + +import java.util.*; + +/** + * A {@link RandomSampling} decorator that doesn't permit duplicate items. + * + * @param the element type + * @param the {@link RandomSampling} implementation type + */ +@Deprecated +class IdentityRandomSampling> implements RandomSampling { + private RS source; + private Set set; + + /** + * Decorates {@code source} as an {@link IdentityRandomSampling}. + *

+ * The caller must ensure that {@code source} will not be accessed directly after this point. + * + * @param source the source {@link RandomSampling} implementation + * @throws NullPointerException if {@code source} is {@code null} + * @throws IllegalArgumentException if {@code source} already had some items feeded + */ + IdentityRandomSampling(RS source) { + if (source == null) { + throw new NullPointerException(); + } + if (source.sample().size() != 0) { + throw new IllegalArgumentException(); + } + this.source = source; + this.set = new HashSet<>(); + } + + @Override + public RS feed(T item) { + if (item == null) { + throw new NullPointerException(); + } + if (!set.add(item)) { + throw new UnsupportedOperationException(); + } + source.feed(item); + return source; + } + + @Override + public RS feed(Iterator items) { + source.feed(items); + return source; + } + + @Override + public RS feed(Iterable items) { + source.feed(items); + return source; + } + + @Override + public int sampleSize() { + return source.sampleSize(); + } + + @Override + public long streamSize() { + return source.streamSize(); + } + + @Override + public Set sample() { + assert source.sample().stream().distinct().count() == source.sample().stream().distinct().count(); + return new AbstractSet() { + final Collection sample = source.sample(); + + @Override + public Iterator iterator() { + return sample.iterator(); + } + + @Override + public int size() { + return sample.size(); + } + }; + } +}