创建一个简单的布隆过滤器.
添加依赖:
<!-- 布隆过滤器 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
java代码的实现:
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import java.nio.charset.Charset;
/**
* @create: 2021-10-19 21:00
* @author: by 房东的猫
* @program: flink_doit
*/
public class BloomFilterDemo {
public static void main(String[] args) {
/*
参数一 : 字符编码集
参数二 : 添加的key的数量
参数三 : 预期的误判率
*/
BloomFilter<Integer> bloomFilter = BloomFilter.create(Funnels.integerFunnel(), 100000, 0.000000001);
// 添加数据
boolean b1 = bloomFilter.put("阿超".hashCode());
boolean b2 = bloomFilter.put("黑糖".hashCode());
//判断是否存在
System.out.println(bloomFilter.mightContain("阿超".hashCode()));//true
System.out.println(bloomFilter.mightContain("老付".hashCode()));//false
BloomFilter<String> bloomFilter2 = BloomFilter.create(Funnels.stringFunnel(Charset.forName("UTF8")), 100000, 0.001);
// 添加数据
boolean b3 = bloomFilter2.put("阿超");//true
boolean b4 = bloomFilter2.put("黑糖");//false
//判断是否存在
System.out.println(bloomFilter.mightContain("阿超".hashCode()));
System.out.println(bloomFilter.mightContain("小超".hashCode()));
//查看存储多少条数据
long l = bloomFilter.approximateElementCount();
long l1 = bloomFilter2.approximateElementCount();
System.out.println(l+l1);//4
}
}