Bloom Filter Probabilistic Membership (Java)
Implement a Java bloom filter with k hash functions for probabilistic membership testing.
Code
public class BloomFilter {
byte[] bits; int size; int k;
public BloomFilter(int size, int k) { this.size = size; this.k = k; this.bits = new byte[size]; }
int hash(String item, int seed) { int h = seed; for (char c : item.toCharArray()) h = (h * 31 + c) % size; return Math.abs(h) % size; }
public void add(String item) { for (int i = 0; i < k; i++) bits[hash(item, i + 1)] = 1; }
public boolean contains(String item) { for (int i = 0; i < k; i++) if (bits[hash(item, i + 1)] == 0) return false; return true; }
}How it works
Count the class BloomFilter and the functions BloomFilter, add and contains as the entire surface area of Bloom Filter Probabilistic Membership (Java).
Using it
The main signature reads public BloomFilter(int size, int k)
Key statements
public boolean contains(String item) { for (int i = 0; i < k; i++) if (bits[hash(item, i + 1)] == 0) return false; return true; }
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `BloomFilter`, `add`, `contains` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.