Skip to content

Generic Recordinality supporting String, Long, or Integer elements #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/main/java/com/cscotta/recordinality/Recordinality.java
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@
import com.google.common.hash.HashFunction;
import com.google.common.collect.ImmutableSet;

public class Recordinality {
public class Recordinality<T> {

private final int sampleSize;
private final int seed = new Random().nextInt();
@@ -46,7 +46,7 @@ public Recordinality(int sampleSize) {
/*
* Observes a value in a stream.
*/
public void observe(String element) {
public void observe(T element) {
boolean inserted = insertIfFits(element);
if (inserted) modifications.incrementAndGet();
}
@@ -84,8 +84,17 @@ public Set<Element> getSample() {
/*
* Inserts a record into our k-set if it fits.
*/
private boolean insertIfFits(String element) {
long hashedValue = hash.hashString(element).asLong();
private boolean insertIfFits(T element) {
long hashedValue = 0L;

if (element.getClass() == String.class)
hashedValue = hash.hashString((String)element).asLong();
else if (element.getClass() == Long.class)
hashedValue = hash.hashLong((Long)element).asLong();
else if (element.getClass() == Integer.class)
hashedValue = hash.hashInt((Integer)element).asLong();
else
throw new ClassCastException();

// Short-circuit if our k-set is saturated. Common case.
if (hashedValue < cachedMin.get() && kMapSize >= sampleSize)
@@ -141,10 +150,10 @@ public String toString() {
*/
public class Element {

public final String value;
public final T value;
public final AtomicLong count;

public Element(String value) {
public Element(T value) {
this.value = value;
this.count = new AtomicLong(1);
}
Original file line number Diff line number Diff line change
@@ -67,7 +67,7 @@ public Result call() throws Exception {
long start = System.currentTimeMillis();
final double[] results = new double[numRuns];
for (int i = 0; i < numRuns; i++) {
Recordinality rec = new Recordinality(kSize);
Recordinality rec = new Recordinality<String>(kSize);
for (String line : lines) rec.observe(line);
results[i] = rec.estimateCardinality();
}