码迷,mamicode.com
首页 > 其他好文 > 详细

布隆过滤器

时间:2020-10-18 10:13:56      阅读:22      评论:0      收藏:0      [点我收藏+]

标签:util   lse   als   def   不同的   技术   容量   bitset   图片   

什么是布隆过滤器

  • 布隆过滤器(Bloom Filter)是有布隆在 1970 年提出的。它实际上是由一个很长的二进制向量和一系列随机映射函数组成。

  • 是一种数据结构,概率性的数据结果

技术图片

布隆过滤器实现

  1. MyBloomFilter.java
import java.util.Arrays;
import java.util.BitSet;

/**
 * 布隆过滤器
 */
public class MyBloomFilter {
    //布隆过滤器容量
    private static final int DEFAULT_SIZE = 2 << 28;
    // bit 数组,用来存放结果
    private static BitSet bitSet = new BitSet(DEFAULT_SIZE);
    // hash 函数会用到,用来生成不同的 hash 值,可随意设置
    private static final int[] ints = {1, 6, 16, 38, 58, 68};

    // hash 函数,借鉴了 hashmap 的扰动算法
    private int hash(Object key, int i) {
        int h;
        return key == null ? 0 : (i * (DEFAULT_SIZE - 1) & ((h = key.hashCode()) ^ (h >>> 16)));
    }

    // add 方法,计算出 key 的 hash 值,并将对应下标置为 true
    public void add(Object key) {
        Arrays.stream(ints).forEach(i -> bitSet.set(hash(key, i)));
    }

    // 判断 key 是否存在,true 不一定说明 key 存在,但是 false 一定说明不存在
    public boolean isContain(Object key) {
        boolean result = true;
        for (int i : ints) {
            // 短路与,只要有一个 bit 位为false,则返回false
            result = result && bitSet.get(hash(key, i));
        }
        return result;
    }
}
  1. 测试数据
public class MyBloomFilterTest {
    public static void main(String[] args) {
        MyBloomFilter bloomFilter = new MyBloomFilter();
        bloomFilter.add("张学友");
        bloomFilter.add("郭德纲");
        bloomFilter.add("刘德华");
        System.out.println(bloomFilter.isContain("张学友"));
        System.out.println(bloomFilter.isContain("郭德纲"));
        System.out.println(bloomFilter.isContain("刘德华"));
        System.out.println(bloomFilter.isContain("666"));
        System.out.println(bloomFilter.isContain("888"));
    }
}

测试结果:
true
true
true
false
false

参考:
https://blog.csdn.net/qq_33709582/article/details/108407706
https://mp.weixin.qq.com/s/SlfLgsfbvytxNS46fTFUdA

布隆过滤器

标签:util   lse   als   def   不同的   技术   容量   bitset   图片   

原文地址:https://www.cnblogs.com/liyiran/p/13832782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!