布隆过滤器的java实现
时间: 2024-02-23 14:54:17 浏览: 63
布隆过滤器(Bloom Filter)的Java实现方法
以下是布隆过滤器的Java实现示例:
1. 使用Java.util包的BitSet类实现布隆过滤器:
```java
import java.util.BitSet;
public class BloomFilter {
private BitSet bitSet;
private int size;
private int[] seeds;
public BloomFilter(int size, int[] seeds) {
this.size = size;
this.seeds = seeds;
this.bitSet = new BitSet(size);
}
public void add(String value) {
for (int seed : seeds) {
int hash = getHash(value, seed);
bitSet.set(hash, true);
}
}
public boolean contains(String value) {
for (int seed : seeds) {
int hash = getHash(value, seed);
if (!bitSet.get(hash)) {
return false;
}
}
return true;
}
private int getHash(String value, int seed) {
int hash = 0;
for (char c : value.toCharArray()) {
hash = seed * hash + c;
}
return Math.abs(hash) % size;
}
}
```
2. 使用Redis的Bitmap实现布隆过滤器:
```java
import redis.clients.jedis.Jedis;
public class BloomFilter {
private Jedis jedis;
private String key;
private int size;
private int[] seeds;
public BloomFilter(String key, int size, int[] seeds) {
this.key = key;
this.size = size;
this.seeds = seeds;
this.jedis = new Jedis("localhost");
}
public void add(String value) {
for (int seed : seeds) {
int hash = getHash(value, seed);
jedis.setbit(key, hash, true);
}
}
public boolean contains(String value) {
for (int seed : seeds) {
int hash = getHash(value, seed);
if (!jedis.getbit(key, hash)) {
return false;
}
}
return true;
}
private int getHash(String value, int seed) {
int hash = 0;
for (char c : value.toCharArray()) {
hash = seed * hash + c;
}
return Math.abs(hash) % size;
}
}
```
阅读全文